简体   繁体   中英

How to copy xml from files and create a new xml file, but exclude certain lines?

I have two xml documents (doc1.xml and doc2.xml)

I want to copy the combine content from doc1.xml and doc2.xml in a new file but I want to exclude two lines.

Both doc1.xml and doc2.xml has a similar structure:

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

I want to copy the xml from the one file into the second file to create a new file, BUT I want to exclude the first node (line) of one of the documents to look like this:

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

My problem is I get the document to look like:

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

My code sample:

    XmlDocument doc1 = new XmlDocument();
        doc1.Load("book.xml");

        XmlDocument doc2 = new XmlDocument();
        doc2.Load("alsobook.xml");

        XmlNode copiedNode = doc2.ImportNode(doc1.SelectSingleNode("/A"), true);
        doc2.DocumentElement.AppendChild(copiedNode);

        XmlNodeList nodes = doc2.SelectNodes("/A/A");

        for (int i = 0; i < nodes.Count ; ++i)
        {
            nodes[i].RemoveChild(nodes[i])
        }

        string fileName = @"C:\Users\Administrator\source\repos\StyleProfileTest\StyleProfileTest\bin\MyNewFile.xml";
        if (!File.Exists(fileName))
        {
            doc2.Save(fileName);
        }

Check it out.

c#, LINQ to XML

void Main()
{
    const string doc1 = @"e:\Temp\Doc1.xml";
    const string doc2 = @"e:\Temp\Doc2.xml";
    const string doc3 = @"e:\Temp\Doc3.xml";

    XDocument xdoc1 = XDocument.Load(doc1);
    XDocument xdoc2 = XDocument.Load(doc2);
    
    var xelem = xdoc1.Descendants("b");
    xdoc2.Root.AddFirst(xelem);
    xdoc2.Save(doc3);
}

You really don't want to use low-level DOM coding for this kind of thing.

In XSLT it's simply:

<a xsl:version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:copy-of select="document('doc1.xml')//b"/>
  <xsl:copy-of select="document('doc2.xml')//b"/>
</a>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM