Copying part of an xml document to another document using Xdocument

天大地大妈咪最大 提交于 2020-01-03 05:17:08

问题


I have an xml document which is roughly as follows

<Gov>
    <Head>
        <address></address>
        <address></address>
    </Head>
    <Body>
        <line1></line1>
        <line1></line1>
    </Body>
<Gov>

I need to copy everything in the body(and including) to a new XDocument. What is the best way to


回答1:


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.




回答2:


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());


来源:https://stackoverflow.com/questions/16584641/copying-part-of-an-xml-document-to-another-document-using-xdocument

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!