简体   繁体   English

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

[英]Find or create an element by xpath using LINQ-to-XML

Does anyone have a neat way of finding or creating an XObject using an xpath expression. 有没有人使用xpath表达式找到或创建XObject的简洁方法。

The problem I am having is that I need to set a value on an element (which I have the xpath for), which may or not be in existence. 我遇到的问题是我需要在一个元素(我有xpath)上设置一个值,这个值可能存在也可能不存在。 If it's not in existence I would like it to be created. 如果它不存在,我希望它被创建。

Any hints or links would be very much appreciated. 非常感谢任何提示或链接。

Thanks all. 谢谢大家。

You can use the System.Xml.XPath.Extensions class to evaluate XPath expressions on an XDocument. 您可以使用System.Xml.XPath.Extensions类来评估XDocument上的XPath表达式。

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

For example: 例如:

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

Assuming a simple path, and you just want to add some data at the end of it. 假设一个简单的路径,你只想在它的末尾添加一些数据。

Starting with some example data: 从一些示例数据开始:

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>
");

This won't work because the product node doesn't exist: 这不起作用,因为产品节点不存在:

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

To do this you could define your own extension method: 为此,您可以定义自己的扩展方法:

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);
    }
}

And chain these together to create your new path. 并将这些链接在一起以创建您的新路径。

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

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

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