Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fragmented XML string parsing with Linq

Tags:

c#

.net

xml

linq

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

<A>
  <B></B>
</A>
<A>
  <B></B>
</A>

I can use XmlReader with Fragment option to parse this not complete XML string.

XmlReaderSettings settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Fragment;
XmlReader reader;
using (StringReader stringReader = new StringReader(inputXml))
{
    reader = XmlReader.Create(stringReader, settings);
}
XPathDocument xPathDoc = new XPathDocument(reader);
XPathNavigator rootNode = xPathDoc.CreateNavigator();
XPathNodeIterator pipeUnits = rootNode.SelectChildren("A", string.Empty);
while (pipeUnits.MoveNext())

Can I do this fragmented XML string parsing with Linq?

like image 810
prosseek Avatar asked May 24 '11 18:05

prosseek


2 Answers

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);
        }
    }
}
like image 118
svick Avatar answered Sep 27 '22 18:09

svick


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.

like image 42
Justin Breitfeller Avatar answered Sep 27 '22 18:09

Justin Breitfeller