Joan Venge
Joan Venge

Reputation: 331102

How to get a value from an xml directly (preferably using XPath)?

I am trying to get comp1's value in the most simple way in C#. I want to be able to do it with a way that requires least checkes whether an element like Primary is there, etc.

i.e.

//  pseudo code
xmlItem = root.SelectSingleNode "/Primary/Complex?Name='comp1'"

So I can just check if xmlItem is null, or has no elements, instead of doing many checks everytime I access a child node. Here is the xml, but the actual one is more nested, but only the leaf xml node has a specific name that we are looking for.

<?xml version="1.0" ?>
<Primary Type="">
   <Simple Name="smp"></Simple>
   <Complex Name="comp0" Value="123"></Complex>
   <Complex Name="comp1" Value="456"></Complex>
   <Complex Name="comp2" Value="789"></Complex>
</Primary>

Upvotes: 1

Views: 391

Answers (4)

AxelEckenberger
AxelEckenberger

Reputation: 16926

Try

root.SelectSingleNode("/Primary/Complex[@Name='comp1']/@Value");

Upvotes: 2

smencer
smencer

Reputation: 1053

You're going to want to use the XPathDocument and XPathNavigator from the System.Xml.XPath namespace.

XPathDocument fileToParse = new XPathDocument(FullPathToFile);
XPathNavigator fileNavigator = fileToParse.CreateNavigator();
XPathNavigator selected = fileNavigator.SelectSingleNode("./Primary/Complex[@Name='comp1']/@Value");
//selected will be null if your XPath doesn't select anything...
if(selected != null){ Console.WriteLine(selected.Value); }

Upvotes: 0

brabster
brabster

Reputation: 43560

I think the XPath is /Primary/Complex[@Name='comp0']/@Value

By the way, your XML is wrong. No closing tag for Simple, no opening tag for Material. I've assumed </Material> should be </Simple>.

Upvotes: 5

Jeff Sternal
Jeff Sternal

Reputation: 48593

var xmlItem = root.SelectSingleNode("/Primary/Complex[@Name='comp1']/@Value");

Upvotes: 3

Related Questions