Arpit
Arpit

Reputation: 126

get the xmlnode value

I have a xml below First I will do a SelectNode to select .Then I want to do a foreach on two selected nodes and then select for each one respectively.

    <Root>
    <persons>
     <Number>2525</Number>
     <Number>2626</Number>
      <persons>
        <Number>2828</Number>
        <Number>2929</Number>
      </persons>
    </persons>
    </Root>

When running the foreach for the first time,I am getting Age and Name for both Arpit and Tushar using the Xpath =

XmlNodeList outcomelist = each.SelectNodes(".//*[local-name()='persons']/*[local-name()='Number']");

"each" is the current node.

Please help to write the xpath correctly so that I can get the values only for the current node and excluding the child node.

Please note that this xml is only for example purpose.The real xml is very big and tedious to parse.

Upvotes: 0

Views: 56

Answers (1)

JLRishe
JLRishe

Reputation: 101690

I think you need to spend some time getting familiar with XPath because you're using "whatever works" techniques like // and *[local-name() = '...'], and this is getting you into trouble.

To select the top level persons, this XPath should work:

XmlNodeList persons = each.SelectNodes("/Root/persons/Number");

If your XML uses namespaces, then you can do this to select the name:

XmlNodeList age = 
  each.SelectNodes("/*/*[local-name() = 'persons']/*[local-name() = 'Number']");

but as I alluded above, this is a hack and what you should really do in this case is handle namespaces properly.

Upvotes: 0

Related Questions