0

i have an incoming string that can change each time, the string is xml.

the string is being sent from a server after the server has exctracted it from a SQL datatable.

some more info: stock is the table name it has several columns but i used executeReader to only get one.

"<Result>\r\n  <stock>\r\n    <name>cheese</name>\r\n  </stock>\r\n  <stock>\r\n    <name>butter</name>\r\n  </stock>\r\n  <stock>\r\n    <name>MILK</name>\r\n  </stock>\r\n  <stock>\r\n    <name>meat</name>\r\n  </stock>\r\n</Result>"

right now what im doing is saving it into an xmlDocument type and then converting it to string using a method

 private void AddList(XmlDocument xmlDoc)
    {

        string s = (xmlDoc.DocumentElement.InnerText);

        string[] list = s.Split(" ");

        int i = 0;
        while(i<list.Length)
        {
            TypeCB.Items.Add(list[i]);// typeCB is a combo box which i want to have the name of the items that were sent
            i++;
        }

    }

this add cheesebutterMILKmeat as one option while i want it to be 4 diffrent ones.

obviously the problem is that what is being saved is one continues string and so the program cant split it at a " " because those dont exist.

how can i split the incoming text?

  • 1
    Are you saying the elements can change (stock, name) or are you saying just the value (cheese, butter) can change? If only value changes you should be parsing the xml nodes instead of getting the entire document text. – Crowcoder Apr 23 '22 at 11:58
  • 3
    _"String.Split()"_ - [Never never never never never use regex or any other string manipulation tools with hierarchical text payloads such as XML or HTML across nodes.](https://stackoverflow.com/a/1732454/585968). Always use the appropriate API –  Apr 23 '22 at 12:13

1 Answers1

1

In this example I am using XDocument from the System.Xml.Linq namespace, instead of XmlDocument.

Assuming you can use XDocument, you can loop over the stock nodes and then select their name nodes.

// do something like this instead of how you create your XmlDocument:
string xml = "<Result>\r\n  <stock>\r\n    <name>cheese</name>\r\n  </stock>\r\n  <stock>\r\n    <name>butter</name>\r\n  </stock>\r\n  <stock>\r\n    <name>MILK</name>\r\n  </stock>\r\n  <stock>\r\n    <name>meat</name>\r\n  </stock>\r\n</Result>";

XDocument doc = XDocument.Parse(xml);

//Once you have the parsed xml you can select the node values and add them to the combobox
foreach (XElement el in doc.Descendants("stock"))
{
    string name = el.Element("name").Value;
    TypeCB.Items.Add(name);
}
Crowcoder
  • 11,250
  • 3
  • 36
  • 45