Node in XML

P

Peter Morris

I have loaded the following XML into an XmlDocument

<email>
<subject>Hello</subject>
<body>Hello</body>
</email>

How do I get the values of both subject and body?


Ta


Pete
 
B

Bjørn Brox

Peter Morris skrev:
I have loaded the following XML into an XmlDocument

<email>
<subject>Hello</subject>
<body>Hello</body>
</email>

How do I get the values of both subject and body?
Several ways, just take a look on the XmlDocument element.

You can access the top level node by xml_doc.DocumentElement and
traversing down the three, or simply use an xpath addressing of the node
of interest.

Example:
String subject_text =
xml_doc.DocumentElement.SelectSingleNode("subject").InnerText;

or
subject_text =
xml_doc.DocumentElement.SelectSingleNode("//email/subject").InnerText;

if your top level element is <email>

If you have several elements like this:
<elist>
<email>
<subject>Hello</subject>
<body>Hello</body>
</email>
<email>
<subject>Hello Again</subject>
<body>Hello, hello</body>
</email>
</elist>

you can pick each element like this (there are several ways of parsing a
xml document on):

foreach (XmlNode n in xml_doc.DocumentElement.SelectNodes("email"))
{
String subj = n.SelectSingleNode("subject").InnerText;
String body = n.SelectSingleNode("body").InnerText;
}
 
P

Peter Morris

This did the trick, thankyou!



string subject = emailDocument.SelectSingleNode("email/subject").InnerText;

string body = emailDocument.SelectSingleNode("email/body").InnerText;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top