1

Currently, I have the xml as the following:

<Node_Parent>

 <Column name="ColA" value="A" />
 <Column name="ColB" value="B" />
 <Column name="ColC" value="C" />
</Node_Parent>

How to get value B at ColB? I tried to use XmlDocument.SelectSingleNode("Node_Parent"), but I cannot access to ColB?

If I change to <ColB value="B" />, I can use XmlDocument.SelectSingleNode("Node_Parent/ColB").Attributes["value"].Value, but the xml format doesn't look good?

Thanks.

Henrik Aasted Sørensen
  • 6,966
  • 11
  • 51
  • 60
Lang thang
  • 281
  • 1
  • 2
  • 11
  • What do you mean by "doesn't look good"? Also, are you able to use LINQ to XML instead of XmlDocument? It's certainly possible to do what you want with XmlDocument and XPath, but I'd personally use LINQ to XML. – Jon Skeet Dec 11 '12 at 10:20
  • Look for similar question: http://stackoverflow.com/questions/13700375/how-do-i-save-an-xml-nodes-content-to-a-string/13700556 – Vitaliy Dec 11 '12 at 10:21
  • Did you try an xpath such as /Node_Parent/Column[@Name = 'ColB']/@value ? – Marcus Dec 11 '12 at 10:24
  • Is it the actual XML? IF not, beware of the possible namespace in the xml. This will have to be specified if nodes are in a namespace – Steve B Dec 11 '12 at 10:24
  • hi all, I'm very appriciated for you help. Finally, I've got the result, it save me a lot of time. – Lang thang Dec 12 '12 at 02:51

1 Answers1

2

You need to write an XPath query in the SelectSingleNode:

var value = doc.SelectSingleNode(
    "Node_Parent/Column[@name = 'ColB']"
    ).Attributes["value"].Value;

For more info on the XPath query language, see http://www.w3schools.com/xpath.

Good luck!

Steve B
  • 36,818
  • 21
  • 101
  • 174
Roy Dictus
  • 32,551
  • 8
  • 60
  • 76