LINQ到XML - 从文件加载XML片段 [英] LINQ to XML - Load XML fragments from file

查看:136
本文介绍了LINQ到XML - 从文件加载XML片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个根元素进来,有什么我可以做的源XMLFILES。什么将这些片段加载到一个XDocument与我可以创建有一个有效的XML文档一个根节点的最佳方式?

I have source XMLfiles that come in with multiple root elements and there is nothing I can do about it. What would be the best way to load these fragments into an XDocument with a single root node that I can create to have a valid XML document?

示例:

<product></product>
<product></product>
<product></product>

应该是这样的:

<products>
  <product></product>
  <product></product>
  <product></product>
</products>

谢谢!

推荐答案

下面是如何使用做一个的XmlReader ,这可能是最灵活和最快速执行的方法

Here's how to do it with an XmlReader, which is probably the most flexible and fastest-performing approach:

XmlReaderSettings xrs = new XmlReaderSettings();
xrs.ConformanceLevel = ConformanceLevel.Fragment;

XDocument doc = new XDocument(new XElement("root"));
XElement root = doc.Descendants().First();

using (StreamReader fs = new StreamReader("XmlFile1.xml"))
using (XmlReader xr = XmlReader.Create(fs, xrs))
{
    while(xr.Read())
    {
        if (xr.NodeType == XmlNodeType.Element)
        {
            root.Add(XElement.Load(xr.ReadSubtree()));                
        }
    }
}

这篇关于LINQ到XML - 从文件加载XML片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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