如何在Linq-to-XML中按路径查找XML节点 [英] How do I find a XML node by path in Linq-to-XML

查看:162
本文介绍了如何在Linq-to-XML中按路径查找XML节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我以字符串的形式获取到特定节点的路径,则可以使用XElement(或XDocument)的Linq/Method轻松地找到该节点.

If I get the path to a specific node as a string can I somehow easily find said node by using Linq/Method of the XElement ( or XDocument ).

有许多不同类型的XML对象,如果可以作为一个额外的好处,让我指向为什么/如何使用不同类型的指南,那也很好.

There are so many different types of XML objects it would also be nice if as a added bonus you could point me to a guide on why/how to use different types.

好的,在指向XPathSelectElement之后,我正在尝试它,所以我可以给他正确的答案,但是我不能完全使它起作用.这是我正在尝试的XML

Ok after being pointed towards XPathSelectElement I'm trying it out so I can give him the right answer I can't quite get it to work though. This is the XML I'm trying out

<Product>
  <Name>SomeName</Name>
  <Type>SomeType</Type>
  <Quantity>Alot</Quantity>
</Product>

和我的代码

string path = "Product/Name";
string name = xml.XPathSelectElement(path).Value;

请注意我的字符串来自其他地方,所以我猜它不必是原义的(至少在调试模式下,它看起来像上面的字符串).我也尝试在前面加/.它给了我一个空引用.

note my string is coming from elsewhere so I guess it doesn't have to be literal ( at least in debug mode it looks like the one above). I've also tried adding / in front. It gives me a null ref.

推荐答案

尝试使用XElementXPathSelectElement扩展方法.您可以将方法传递给XPath表达式进行评估.例如:

Try using the XPathSelectElement extension method of XElement. You can pass the method an XPath expression to evaluate. For example:

XElement myElement = rootElement.XPathSelectElement("//Book[@ISBN='22542']");

修改:

要回复您的编辑,请检查您的XPath表达式.如果您的文档仅包含该小片段,则/Product/Name将起作用,因为前导斜杠从文档的根目录执行搜索:

In reply to your edit, check your XPath expression. If your document only contains that small snippet then /Product/Name will work as the leading slash performs a search from the root of the document:

XElement element = document.XPathSelectElement("/Product/Name");

如果还有其他产品,并且<Product>不是根节点,则需要修改正在使用的XPath.

If there are other products and <Product> is not the root node you'll need to modify the XPath you're using.

这篇关于如何在Linq-to-XML中按路径查找XML节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆