Connecting Tech Pros Worldwide Help | Site Map

looping through XML nodes

 
LinkBack Thread Tools Search this Thread
  #1  
Old November 12th, 2005, 01:29 AM
Praveen Naregal
Guest
 
Posts: n/a
Default looping through XML nodes

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, 01:29 AM
Leszek
Guest
 
Posts: n/a
Default 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]


 

Bookmarks

Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

Popular Articles

What is Bytes?

We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights. Get the best answers to your questions from over 220,662 network members.