Connecting Tech Pros Worldwide Help | Site Map

looping through XML nodes

  #1  
Old November 12th, 2005, 02:29 AM
Praveen Naregal
Guest
 
Posts: n/a
hello all,

I have a problem. I have an XML file like below one.I want to loop through
node by node and store or display the data .

Can anybody give me a sample piece of c# code?

Thanks & Regards,

Praveen



<?xml version="1.0" encoding="utf-8" ?>
<book id=1>

<name>abc</name>

<title>xyz</title>

</book>

<book id=2>

<name>pqr</name>

<title>lmn</title>

</book>



  #2  
Old November 12th, 2005, 02:29 AM
Leszek
Guest
 
Posts: n/a

re: looping through XML nodes


First of all you have to wrap the code into a root element. I used <books>
<?xml version="1.0" encoding="utf-8" ?>
<books>
<book id=1>
<name>abc</name>
<title>xyz</title>
</book>
<book id=2>
<name>pqr</name>
<title>lmn</title>
</book>
</books>

You can use an XmlReader, but I traverse all nodes. It gives me flexibility
with selecting only elements I need:

XmlDocument doc = new XmlDocument();
doc.Load("doc.xml");
XmlElement root = doc.DocumentElement;
XmlNodeList nodes = root.SelectNodes("/books"); // You can filter elements
here using XPath
foreach (XmlNode node in nodes)
{
string name = node["name"].InnerText;
string title = node["title"].InnerText;
// Do whatever you want
Console.Write("name\t{0}\title\t{1}", name, title);
}

"Praveen Naregal" <pgnaregal@hotmail.com> wrote in message
news:u2EdskO4DHA.2680@TK2MSFTNGP11.phx.gbl...[color=blue]
> hello all,
>
> I have a problem. I have an XML file like below one.I want to loop through
> node by node and store or display the data .
>
> Can anybody give me a sample piece of c# code?
>
> Thanks & Regards,
>
> Praveen
>
>
>
> <?xml version="1.0" encoding="utf-8" ?>
> <book id=1>
>
> <name>abc</name>
>
> <title>xyz</title>
>
> </book>
>
> <book id=2>
>
> <name>pqr</name>
>
> <title>lmn</title>
>
> </book>
>
>
>[/color]


Closed Thread


Similar Threads
Thread Thread Starter Forum Replies Last Post
Looping through XML li72 answers 2 March 11th, 2008 09:35 PM
SelectSingleNode always selects same node when looping through Claire Reed answers 2 November 12th, 2005 03:56 AM
Looping through nested XML Cappy answers 2 November 12th, 2005 02:58 AM
looping through names of nodes and sub nodes k.a.bouton@reading.ac.uk answers 5 September 22nd, 2005 05:15 PM