How can I query an XDocument with a 'path'

2019-03-22 19:53发布

I would like to query an XDocument object for a given path, (e.g. "/path/to/element/I/want") but I don't know how to proceed.

4条回答
不美不萌又怎样
2楼-- · 2019-03-22 20:19

I needed to do something similar. This repo has several unit tests demoing XDocument querying with XPathEvaluate()

查看更多
倾城 Initia
3楼-- · 2019-03-22 20:20

Even though this is a somewhat older post, it should be noted that LINQ-to-XML can be used as an alternative to System.XML.XPath to find elements based on a path within an XDocument

Example:

var results = x.Elements("path").Elements("to").Elements("element").Elements("I").Elements("want").FirstOrDefault();

Note: The LINQ to XML command may need to be altered to accommodate for the actual structure and/or cardinality of the XML.

https://msdn.microsoft.com/en-us/library/bb675156.aspx

查看更多
可以哭但决不认输i
4楼-- · 2019-03-22 20:27

Something similar to this might work:

var path = "/path/to/element/I/want";
var route = path.Split(new []{'/'}, StringSplitOptions.RemoveEmptyEntries);

XElement result = null;
foreach (var node in route)
{
    if (result == null)
    {
        result = _xmlDocument.Element(node);    
    }
    else
    {
        result = result.Element(node);
    }
}

return result;
查看更多
仙女界的扛把子
5楼-- · 2019-03-22 20:30

You can use methods from System.Xml.XPath.Extensions to do this.

For example, if you want to select a single element, you would use XPathSelectElement():

var element = doc.XPathSelectElement("/path/to/element/I/want");

The queries don't have to be simple paths like what you described, they use the XPath language.

查看更多
登录 后发表回答