LINQ to XML - Load XML fragments from file

后端 未结 3 948
伪装坚强ぢ
伪装坚强ぢ 2020-12-03 11:04

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

3条回答
  •  心在旅途
    2020-12-03 11:57

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

提交回复
热议问题