Fragmented XML string parsing with Linq

前端 未结 2 784
一整个雨季
一整个雨季 2020-12-07 02:55

Let\'s say I have a fragmented XML as follows.


  


  

I can

相关标签:
2条回答
  • 2020-12-07 03:36

    Using the XNode.ReadFrom() method, you can easily create a method that returns a sequence of XNodes:

    public static IEnumerable<XNode> ParseXml(string xml)
    {
        var settings = new XmlReaderSettings
        {
            ConformanceLevel = ConformanceLevel.Fragment,
            IgnoreWhitespace = true
        };
    
        using (var stringReader = new StringReader(xml))
        using (var xmlReader = XmlReader.Create(stringReader, settings))
        {
            xmlReader.MoveToContent();
            while (xmlReader.ReadState != ReadState.EndOfFile)
            {
                yield return XNode.ReadFrom(xmlReader);
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-07 03:36

    I'm not exactly an expert on this topic, but I can't see why this method wouldn't work:

    XDocument doc = XDocument.Parse("<dummy>" + xmlFragment + "</dummy>");
    

    The one thing about using this approach is that you have to remember that a dummy node is the root of your document. Obviously, you could always just query on the child Nodes property to get the information you need.

    0 讨论(0)
提交回复
热议问题