使用XPath查询XML字符串的最优雅方式

Sco*_*ach 14 c# xml xpath

我想知道在C#中使用XPath查询有效xml的STRING最优雅的方法是什么?

目前,我正在这样做(使用LINQ):

var el = XElement.Parse(xmlString);
var h2 = el.XPathSelectElement("//h2");
Run Code Online (Sandbox Code Playgroud)

Tho*_*que 19

使用Linq to XML的简单示例:

XDocument doc = XDocument.Parse(someStringContainingXml);
var cats = from node in doc.Descendants("Animal")
           where node.Attribute("Species").Value == "Cat"
           select node.Attribute("Name").Value;
Run Code Online (Sandbox Code Playgroud)

比XPath恕我直言更清楚......

  • 可能比XPath更干净但不回答问题. (4认同)

Mar*_*tke 5

只是为了记录,我不想使用 Linq2XML 而是使用 XPath 并找到了这种方式:

var xPathDoc = new XPathDocument(new StringReader("your XML string goes here"));
Run Code Online (Sandbox Code Playgroud)