tags:

views:

68

answers:

4

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>
+2  A: 

Try

root.SelectSingleNode("/Primary/Complex[@Name='comp1']/@Value");
Obalix
+3  A: 
var xmlItem = root.SelectSingleNode("/Primary/Complex[@Name='comp1']/@Value");
Jeff Sternal
+5  A: 

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>.

Brabster
Yes, it's my mistake.
Joan Venge
A: 

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); }
smencer