开发者

LINQ to XML - Load XML fragments from file

开发者 https://www.devze.com 2022-12-21 17:10 出处:网络
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 tha

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?

Sample:

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

Sh开发者_JAVA技巧ould be something like:

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

Thanks!


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


I'll leave you to put it into a string field, but you can basically do this:

myDoc=new XmlDocument();
myDoc.LoadXml("<products>"+myData+"</products>");


roughly, something like.

var newXML= new XElement("products",
               from x in Xdocuments.parse(originalFile).descendants("product")                       
               select new XElement("product",x.value)
            );
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号