Home > Net >  i need to find a way to split an xml document into different strings
i need to find a way to split an xml document into different strings

Time:04-23

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?

CodePudding user response:

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);
}
  • Related