使用LINQ-to-XML通过xpath查找或创建元素

问题描述 投票:7回答:2

有没有人使用xpath表达式找到或创建XObject的简洁方法。

我遇到的问题是我需要在一个元素(我有xpath)上设置一个值,这个值可能存在也可能不存在。如果它不存在,我希望它被创建。

非常感谢任何提示或链接。

谢谢大家。

c# linq-to-xml xpath
2个回答
1
投票

您可以使用System.Xml.XPath.Extensions类来评估XDocument上的XPath表达式。

http://msdn.microsoft.com/en-us/library/system.xml.xpath.extensions.aspx

例如:

using System.Xml.XPath;
...
XDocument doc = XDocument.Load("sample.xml");
var matching = doc.XPathEvaluate("//Book[@Title='Great Expectations']");  
// 'matching' could be an IEnumerable of XElements, depending on the query

0
投票

假设一个简单的路径,你只想在它的末尾添加一些数据。

从一些示例数据开始:

var xml = XDocument.Parse(@"<?xml version=""1.0""?>
<messages>
  <request type=""MSG"">
    <header>
      <datestamp>2019-02-26T14:49:41+00:00</datestamp>
      <source>1</source>
    </header>
    <body>
      <title>Hi there</title>
    </body>
  </request>
</messages>
");

这不起作用,因为产品节点不存在:

xml.XPathSelectElement("/messages/request/body/product")
    ?.Add(new XElement("description", "A new product"));

为此,您可以定义自己的扩展方法:

public static class extensionMethods
{
    public static XElement FindOrAddElement(this XContainer xml, string nodeName)
    {
        var node = xml.Descendants().FirstOrDefault(x => x.Name == nodeName);
        if (node == null)
            xml.Add(new XElement(nodeName));
        return xml.Descendants().FirstOrDefault(x => x.Name == nodeName);
    }
}

并将这些链接在一起以创建您的新路径。

xml.FindOrAddElement("messages")
   .FindOrAddElement("request")
   .FindOrAddElement("body")
   .FindOrAddElement("product")
   ?.Add(new XElement("description", "A new product"));
© www.soinside.com 2019 - 2024. All rights reserved.