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

查看:52
本文介绍了将 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.

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

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天全站免登陆