使用Xdocument将xml文档的一部分复制到另一个文档 [英] Copying part of an xml document to another document using Xdocument

查看:95
本文介绍了使用Xdocument将xml文档的一部分复制到另一个文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个xml文档,大致如下

I have an xml document which is roughly as follows

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

我需要将正文(包括其中)中的所有内容复制到新的XDocument.

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

推荐答案

下面是将数据"xml"从一个文档复制到另一个文档的示例.选择个性化节点

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

首先,您需要将Xdocument转换为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);
            }
        }
    }
}

现在使用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);

更多信息在这里:

  1. http://blog.project-sierra.de/archives/1050
  2. 将Xml元素复制到C#中的另一个文档中
  3. 将XDocument转换为XmlDocument,反之亦然
  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

希望这对您有所帮助.

这篇关于使用Xdocument将xml文档的一部分复制到另一个文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆