转换的XDocument到XmlDocument的,反之亦然 [英] Converting XDocument to XmlDocument and vice versa

查看:187
本文介绍了转换的XDocument到XmlDocument的,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个非常简单的问题,我有。我使用的XDocument生成XML文件。那么我想它返回一个XmlDocument类。
我有一个XmlDocument变量,我需要转换回的XDocument追加多个节点。

It's a very simple problem that I have. I use XDocument to generate an XML file. I then want to return it as a XmlDocument class. And I have an XmlDocument variable which I need to convert back to XDocument to append more nodes.

那么,什么是的最有效的的方法将XML转换的XDocument和XmlDocument的之间? (没有在文件中使用的任何临时存储。)

So, what is the most efficient method to convert XML between XDocument and XmlDocument? (Without using any temporary storage in a file.)

推荐答案

您可以使用内置的xDocument.CreateReader()和XmlNodeReader对象来回转换。

You can use the built in xDocument.CreateReader() and an XmlNodeReader to convert back and forth.

把该进的扩展方法,使其更易于使用。

Putting that into an Extension method to make it easier to work with.

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

来源:

这篇关于转换的XDocument到XmlDocument的,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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