English 中文(简体)
如何直接从 XML 中获取一个值(最好使用 XPath)?
原标题:How to get a value from an xml directly (preferably using XPath)?

我正在尝试以最简单的方式在C#中获取comp1的值。我希望能够以一种最少需要检查元素(如Primary是否存在)的方式来完成。

即。

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

因此,我只需检查xmlItem是否为null或没有元素,而不是每次访问子节点时进行多次检查。这是xml,但实际上更嵌套,但只有叶xml节点具有我们正在查找的特定名称。

<?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>
最佳回答
var xmlItem = root.SelectSingleNode("/Primary/Complex[@Name= comp1 ]/@Value");
问题回答

我想XPath是/Primary/Complex[@Name= comp0]/@Value

顺便说一下,你的XML有问题。Simple没有关闭标签,Material没有开放标签。我假设</Material>应该是</Simple>

试一试

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

您需要使用System.Xml.XPath命名空间中的XPathDocument和XPathNavigator。

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




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签