navigate to correct XML node ??

T

Timothy W. Molter

<root>
<person>
<name>bob</name>
<age>30</age>
</person>
<person>
<name>bill</name>
</person>
</root>

I'd like to navigate to the LAST "person" node and insert an "age"
element.

if I use*:
XmlNode insertNode = xmlDoc.SelectSingleNode("/root/person");
and
XmlElement xe = xmlDoc.CreateElement("age");
xe.innerText = "40";
insertNode.AppendChild(xe);
, a new "age element is inserted in the FIRST "person" node.

*not the complete code, but the main idea

How can I insert my "age" element in the LAST "person" node of the
xmlDoc?

Thanks much, Tim :)
 
A

Aneesh Pulukkul[MCSD.Net]

<root>
<person>
<name>bob</name>
<age>30</age>
</person>
<person>
<name>bill</name>
</person>
</root>

I'd like to navigate to the LAST "person" node and insert an "age"
element.

if I use*:
XmlNode insertNode = xmlDoc.SelectSingleNode("/root/person");
and
XmlElement xe = xmlDoc.CreateElement("age");
xe.innerText = "40";
insertNode.AppendChild(xe);
, a new "age element is inserted in the FIRST "person" node.

*not the complete code, but the main idea

How can I insert my "age" element in the LAST "person" node of the
xmlDoc?

Thanks much, Tim :)

Can you use XmlNode.LastChild property to get the last person node
among childnodes?
 
M

Miroslav Stampar [MCSD.NET / Security+]

XmlNode node = xmlDoc.DocumentElement.LastChild;
node.AppendChild(xmlDoc.CreateElement("age"));

HTH :)
 
T

Timothy W. Molter

thanks for the reply!

Yes, I could use that, but it's not exactly going to work for me.
After I posted. I realized you might post that solution, and I should
have stated my problem differently. If I have this XML:

<root>
<person>
<name>bob</name>
<age>30</age>
</person>
<person>
<name>bill</name>
</person>
<bike>
<brand>Trek</brand>
<color>blue</color>
</bike>
</root>

How can I insert an "age" element in the LAST "person" node of the
xmlDoc?

I hope you can answer that!

Thanks again, Tim
 
A

Aneesh Pulukkul[MCSD.Net]

thanks for the reply!

Yes, I could use that, but it's not exactly going to work for me.
After I posted. I realized you might post that solution, and I should
have stated my problem differently. If I have this XML:

<root>
<person>
<name>bob</name>
<age>30</age>
</person>
<person>
<name>bill</name>
</person>
<bike>
<brand>Trek</brand>
<color>blue</color>
</bike>
</root>

How can I insert an "age" element in the LAST "person" node of the
xmlDoc?

I hope you can answer that!

Thanks again, Tim

Use XmlDataDocument.SelectNodes(string xPath) method providing path
for person node - "/root/person"
 

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