How to find first XML occurrence of <elementName> via SelectSinglenode?

  • Thread starter Thread starter sherifffruitfly
  • Start date Start date
S

sherifffruitfly

Hi,

Last question (promise). I want to write out a new XML row, tacked onto
the end of everything contained under the first <elementName> section.
I can do the write, I'm just not sure what the xpath is to complete the
following:

XmlElement el = (XmlElement)cdjDoc.SelectNodes(@"first element named
elementName");

Can anyone tell me?

Thanks a jillion - i'll go away now :)
 
sherifffruitfly said:
Hi,

Last question (promise). I want to write out a new XML row, tacked onto
the end of everything contained under the first <elementName> section.
I can do the write, I'm just not sure what the xpath is to complete the
following:

XmlElement el = (XmlElement)cdjDoc.SelectNodes(@"first element named
elementName");

Can anyone tell me?

Thanks a jillion - i'll go away now :)

Without knowing your full XML document, it sounds like you want to use a
positional predicate to get the first node. Using your Soldiers example
from earlier, if you wanted to select the first Soldier under Soldiers you
would use the following:

XmlNode firstSoldier = xDoc.SelectSingleNode("Soldiers/Soldier[1]");
 
Hello!

XmlNode firstSoldier = xDoc.SelectSingleNode("Soldiers/Soldier");

Actually, you don't need to specify the indexer as XmlNode.SingleNode
returns the first node if the query results in a XmlNodeList. I like the
explicit query, but I think its worth knowing there's another way to write
the query :-)
 
Anders said:
Hello!

XmlNode firstSoldier = xDoc.SelectSingleNode("Soldiers/Soldier");

Actually, you don't need to specify the indexer as XmlNode.SingleNode
returns the first node if the query results in a XmlNodeList. I like the
explicit query, but I think its worth knowing there's another way to write
the query :-)

Ack - this assumes what I previously said about the structure of my XML
document. I have since found out that there are a few different formats
that my XML files could be in, and the <Soldiers> section could be in a
few different places.

I need to obtain the first <Soldiers> element *wherever* it may lie in
the XML document - with no assumptions being made about the document's
structure.

Sorry I didn't say explicitly that I've had to give up my assumptions
about the XML files.

But thanks for the answers!

cdj
 
It's
XmlNode firstSoldier = xDoc.SelectSingleNode("//Soldier");

hth
 
Christof said:
It's
XmlNode firstSoldier = xDoc.SelectSingleNode("//Soldier");

hth

It helped very much - thanks for the help everyone!

cdj
 

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

Back
Top