Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In the example you present the only thing being created is the attribute ... </p> <pre><code>XmlElement element = (XmlElement)doc.SelectSingleNode("/feed/entry/content"); if (element != null) element.SetAttribute("source", ""); </code></pre> <p>If what you really want is to be able to create the hierarchy where it doesn't exist then you could your own simple xpath parser. I don't know about keeping the attribute in the xpath though. I'd rather cast the node as an element and tack on a .SetAttribute as I've done here:</p> <pre><code> static private XmlNode makeXPath(XmlDocument doc, string xpath) { return makeXPath(doc, doc as XmlNode, xpath); } static private XmlNode makeXPath(XmlDocument doc, XmlNode parent, string xpath) { // grab the next node name in the xpath; or return parent if empty string[] partsOfXPath = xpath.Trim('/').Split('/'); string nextNodeInXPath = partsOfXPath.First(); if (string.IsNullOrEmpty(nextNodeInXPath)) return parent; // get or create the node from the name XmlNode node = parent.SelectSingleNode(nextNodeInXPath); if (node == null) node = parent.AppendChild(doc.CreateElement(nextNodeInXPath)); // rejoin the remainder of the array as an xpath expression and recurse string rest = String.Join("/", partsOfXPath.Skip(1).ToArray()); return makeXPath(doc, node, rest); } static void Main(string[] args) { XmlDocument doc = new XmlDocument(); doc.LoadXml("&lt;feed /&gt;"); makeXPath(doc, "/feed/entry/data"); XmlElement contentElement = (XmlElement)makeXPath(doc, "/feed/entry/content"); contentElement.SetAttribute("source", ""); Console.WriteLine(doc.OuterXml); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload