Create a node in an XML document if it does not exist using linq for xml

I am requesting an XML document using the XPathSelectElement method.

if node does not exist, I would like to insert node with this path in the same document. Parent nodes must also be created if they do not exist. Is there an easy way to do this without looping around the parents, checking if they exist? (Add a new node using XPath)

+4
source share
2 answers

No, no ... this is no different from the fact that you were looking for a directory in the file system and had to ensure that all parent directories were there.

Example:

if (Directory.Exists(@":c:\test1\test2\blah blah\blah blah2")) ... 

It is true that the Directory.CreateDirectory method will create all the parents that need to be there to show the children, but there is no equivalent in XML (using .NET classes, including LINQ-to-XML).

You will have to sort through each of them manually. I suggest you create a helper method called "EnsureNodeExists" that will do this for you :)

+1
source
 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("<feed />"); makeXPath(doc, "/feed/entry/data"); XmlElement contentElement = (XmlElement)makeXPath(doc,"/feed/entry/content"); contentElement.SetAttribute("source", ""); Console.WriteLine(doc.OuterXml); } 
0
source

All Articles