Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I have done something like this before. I am using LINQ to XML. I created an extension method for XElement that takes a Queue of node names, and a value for the last node in your list. Here is the extension method I made:</p> <pre><code>/// &lt;summary&gt; /// Creates nessecary parent nodes using the provided Queue, and assigns the value to the last child node. /// &lt;/summary&gt; /// &lt;param name="ele"&gt;XElement to take action on&lt;/param&gt; /// &lt;param name="nodes"&gt;Queue of node names&lt;/param&gt; /// &lt;param name="value"&gt;Value for last child node&lt;/param&gt; public static void UpdateOrCreate(this XElement ele, Queue&lt;string&gt; nodes, string value) { string previousNodeName = ""; int fullQueueCOunt = nodes.Count; for (int i = 0; i &lt; fullQueueCOunt; i++) { string node = nodes.Dequeue(); if (ele.Descendants(node).FirstOrDefault() == null) { if (!string.IsNullOrEmpty(previousNodeName)) { ele.Element(previousNodeName).Add(new XElement(node)); } else { // use main parent node if this is the first iteration ele.Add(new XElement(node)); } } previousNodeName = node; } // assign the value of the last child element ele.Descendants(previousNodeName).First().Value = value; } </code></pre> <p>And here is a sample implementation:</p> <pre><code>XElement element = XElement.Parse( "&lt;employee&gt;" + "&lt;name&gt;John Smith&lt;/name&gt;" + "&lt;/employee&gt;"); Queue&lt;string&gt; nodeQueue = new Queue&lt;string&gt;(); nodeQueue.Enqueue("address"); nodeQueue.Enqueue("city"); element.UpdateOrCreate(nodeQueue, "myValue"); </code></pre> <p>This will take the input XML:</p> <pre><code>&lt;employee&gt; &lt;name&gt;John Smith&lt;/name&gt; &lt;/employee&gt; </code></pre> <p>And change it to:</p> <pre><code>&lt;employee&gt; &lt;name&gt;John Smith&lt;/name&gt; &lt;address&gt; &lt;city&gt;myValue&lt;/city&gt; &lt;/address&gt; &lt;/employee&gt; </code></pre> <p>This will also work if the 'address' and/or 'city' nodes already exist.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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