Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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>

Should be something like:

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

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
158 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...