【问题标题】:Convert XDocument code to XmlDocument将 XDocument 代码转换为 XmlDocument
【发布时间】:2017-05-09 23:12:01
【问题描述】:

大家好,我正在尝试将下面的代码从 XDocument 转换为 XmlDocument(我需要在 XmlDocument 中使用它)您知道需要更改的不同方法吗?我在 XmlDocument 和 XElement 类中查找了其中一些,但我的更改没有编译。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Data;  

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            XElement root = (XElement)doc.FirstNode;

            DataTable dt = new DataTable();
            dt.Columns.Add("Parent", typeof(string));
            dt.Columns.Add("Child", typeof(string));
            dt.Columns.Add("Attribute", typeof(string));
            dt.Columns.Add("Value", typeof(string));

            foreach(XElement parent in root.Elements())
            {
                string parentTag = parent.Name.LocalName;

                foreach (XElement child in parent.Elements())
                {
                    string childTag = child.Name.LocalName;

                    foreach (XAttribute attribute in child.Attributes())
                    {
                        dt.Rows.Add(new object[] { parentTag, childTag, attribute.Name, (string)attribute });
                    }
                }
            }
        }
    }
}

谢谢

【问题讨论】:

  • 这些库彼此完全不同,但只要看看智能感知告诉你做什么,你就可以很快地重构这段代码。
  • 为什么需要进行转换?

标签: c# linq-to-xml xmldocument


【解决方案1】:

与其重构现有代码库,不如将最终的XDocument 读入新的XmlDocument

XDocument xDocument = 
    XDocument.Load("file.xml");

...other manipulations...

XmlDocument xmlDocument =
    new XmlDocument();

// Read the XDocument as a simple XML string:
xmlDocument.LoadXml(xDocument.ToString());

// Alternatively, read the XDocument with an XmlReader:
xmlDocument.Load(xDocument.CreateReader());

【讨论】:

    猜你喜欢
    • 2010-12-03
    • 1970-01-01
    • 1970-01-01
    • 2011-10-19
    • 1970-01-01
    • 1970-01-01
    • 2014-01-17
    • 2010-12-05
    相关资源
    最近更新 更多