Copying part of an xml document to another document using Xdocument

后端 未结 2 1944
谎友^
谎友^ 2020-12-20 10:36

I have an xml document which is roughly as follows


    
        
相关标签:
2条回答
  • 2020-12-20 11:10

    Read in the input XML into one XDocument and construct a second, passing in the node you are interested in:

    XDocument newDoc = new XDocument(XDocument.Load("input.xml").Descendants("Body").First());
    
    0 讨论(0)
  • 2020-12-20 11:12

    Here is an example of copying data "xml" from one document to another.With selection of personalized node

    First you need convert Xdocument to XmlDocument:

    using System;
    using System.Xml;
    using System.Xml.Linq;
    
    namespace MyTest
    {
        internal class Program
        {
            private static void Main(string[] args)
            {
    
                var xmlDocument = new XmlDocument();
                xmlDocument.LoadXml("<Root><Child>Test</Child></Root>");
    
                var xDocument = xmlDocument.ToXDocument();
                var newXmlDocument = xDocument.ToXmlDocument();
                Console.ReadLine();
            }
        }
    
        public static class DocumentExtensions
        {
            public static XmlDocument ToXmlDocument(this XDocument xDocument)
            {
                var xmlDocument = new XmlDocument();
                using(var xmlReader = xDocument.CreateReader())
                {
                    xmlDocument.Load(xmlReader);
                }
                return xmlDocument;
            }
    
            public static XDocument ToXDocument(this XmlDocument xmlDocument)
            {
                using (var nodeReader = new XmlNodeReader(xmlDocument))
                {
                    nodeReader.MoveToContent();
                    return XDocument.Load(nodeReader);
                }
            }
        }
    }
    

    And now simplified copy with XmlDocument

        XmlDocument doc1 = new XmlDocument();
        doc1.LoadXml(@"<Hello>
                               <World>Test</World>
                       </Hello>");
    
        XmlDocument doc2 = new XmlDocument();
        doc2.LoadXml(@"<Hello>
                       </Hello>");
    
        XmlNode copiedNode = doc2.ImportNode(doc1.SelectSingleNode("/Hello/World"), true);
        doc2.DocumentElement.AppendChild(copiedNode);
    

    more information here:

    1. http://blog.project-sierra.de/archives/1050
    2. Copy Xml element to another document in C#
    3. Converting XDocument to XmlDocument and vice versa

    I hope this help you.

    0 讨论(0)
提交回复
热议问题