开发者

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

开发者 https://www.devze.com 2023-02-02 15:52 出处:网络
Does anyone have a neat way of finding or creating an XObject using an xpath expression. The problem I am having is that I need to set a value on an element (which I have the xpath for), which may o

Does anyone have a neat way of finding or creating an XObject using an xpath expression.

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. If it's not in existence I would like it to be created.

An开发者_开发知识库y 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.

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

精彩评论

暂无评论...
验证码 换一张
取 消