简体   繁体   English

如何在Linq-to-XML中按路径查找XML节点

[英]How do I find a XML node by path in Linq-to-XML

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 ). 如果我得到一个特定节点的路径作为字符串,我可以通过使用XElement(或XDocument)的Linq /方法以某种方式轻松找到所述节点。

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. 有很多不同类型的XML对象,如果作为一个额外的奖励,你可以指出我为什么/如何使用不同类型的指南。

EDIT: 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. 编辑:确定在指向XPathSelectElement后我正在尝试它,所以我可以给他正确的答案我不能让它工作但是。 This is the XML I'm trying out 这是我正在尝试的XML

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

and my code 和我的代码

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. 它给了我一个空参考。

Try using the XPathSelectElement extension method of XElement . 尝试使用XElementXPathSelectElement扩展方法。 You can pass the method an XPath expression to evaluate. 您可以将方法传递给XPath表达式进行求值。 For example: 例如:

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

Edit : 编辑

In reply to your edit, check your XPath expression. 在回复您的编辑时,请检查您的XPath表达式。 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: 如果您的文档仅包含该小片段,那么/Product/Name将起作用,因为前导斜杠从文档的根目录执行搜索:

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

If there are other products and <Product> is not the root node you'll need to modify the XPath you're using. 如果有其他产品且<Product>不是根节点,则需要修改您正在使用的XPath。

You can also use XPathEvaluate 您还可以使用XPathEvaluate

XDocument document = XDocument.Load("temp.xml");
var found = document.XPathEvaluate("/documents/items/item") as IEnumerable<object>;
foreach (var obj in found)
{
    Console.Out.WriteLine(obj);    
}

Given the following xml: 给出以下xml:

<?xml version="1.0" encoding="utf-8" ?>
<documents>
  <items>
    <item name="Jamie"></item>
    <item name="John"></item>
  </items>
</documents>

This should print the contents from the items node. 这应该打印items节点中的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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