How to store XPathExpression result to split XML with ancestor structure?

I am parsing a large XML file with XPathExpression selection for some nodes existing at different depth levels.

What's the simplest way to export selected nodes to split an XML file while keeping all direct ancestor nodes (and their attributes)? C # is preferred.

Example XML source:

<a>
  <x>
  <b>
    <c/>
    <z/>
  </b>
  <c/>
</a>
<c/>
<d><e/></d>

      

Expected target XML for filtering repetitions of "c" nodes

<a>
  <b>
    <c/>
  </b>
  <c/>
</a>
<c/>

      

EDIT: I am using XPathExpression and XPathNodeIterator because there is additional logic to test if a given node is to be embedded in the XML result, XPathExpression alone is not enough. So basically I have an array of matching XPathNavigator elements that I want to store in XML with the ancestor structure.

0


source to share


2 answers


string xml = @"<xml>
 <a>
  <x/>
  <b>
    <c/>
    <z/>
  </b>
  <c/>
</a>
<c/>
<d><e/></d></xml>";
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(xml);
    XmlDocument results = new XmlDocument();
    XmlNode root = results.AppendChild(results.CreateElement("xml"));
    foreach (XmlNode node in doc.SelectNodes("/*/*[descendant-or-self::c]"))
    {
        root.AppendChild(results.ImportNode(node, true));
    }
    results.Save("out.xml");

      



+2


source


I used the solution based on Marc above, with a slight modification: I am not using the child or self radio button, but for the selected (and checked) nodes, I use the following workaround:



    private void appendToOut(XmlNode node, XmlNode parameter)
    {
        if (node.ParentNode != null && node.ParentNode.NodeType != XmlNodeType.Document)
        {
            appendToOut(node.ParentNode, node);
        }
        diffRoot.AppendChild(diffDoc.ImportNode(node, node==parameter));
    }

      

0


source







All Articles