Stopbyte

How to read XML Document from memory and go through child nodes using C# and foreach?

Is there any easy way to read my XML formatted string (in memory). the XML string wont have any standard namespaces. as follows:

<doc>
    <nodes>
        <node tag="node1" title="Hello world" description="some text here" />
        <node tag="node2" title="Hello world" description="some text here" />
        <node tag="node3" title="Hello world" description="some text here" />
        <node tag="node4" title="Hello world" description="some text here" />
    </nodes>
</doc>

How can i read and go through those XML nodes of my XML string?

the string is received through a web GET request.

3 Likes

You can load XML from a string using this:

using System.Xml;

First add that using statement to import the necessary namespace for the XML stuff to work.

then do something like the following to load an XmlDocument object type from a string in memory.

// You can load your Xml string from anywhere you want.
string MyXmlString = "<doc>"+
"    <nodes>"
"        <node tag='node1' title='Hello world' description='some text here' />"
"        <node tag='node2' title='Hello world' description='some text here' />"
"        <node tag='node3' title='Hello world' description='some text here' />"
"        <node tag='node4' title='Hello world' description='some text here' />"
"    </nodes>"
"</doc>";

// Declare a new XmlDocument Instance.
XmlDocument doc = new XmlDocument();

/// now load XML from string.
doc.LoadXml(MyXmlString);

// Now go through our XML nodes one by one using foreach.
// This foreach loo below goes through elements of first node of the doc node.
// doc.DocumentElement doesn't mean necessarly our doc node above in the XML,
// but rather means the first root node of the document which is doc in our case here.
foreach (XmlNode node in doc.DocumentElement.ChildNodes[0].ChildNodes)
{
    // you are going through nodes now :)
}
3 Likes

These two lines of code are all you need to do:

var doc = new XmlDocument();
doc.LoadXml("<xml><root tag="Hello World!"></root></xml>");

Then you can handle the XML Document nodes tree the way you want.

2 Likes