简体   繁体   中英

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.

ie

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

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

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

尝试

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM