Parse XML fragmented string using Linq

Let's say I have fragmented XML as follows.

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

I can use the XmlReader with the Fragment parameter 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 fragmented parsing of XML strings using Linq?

+4
source share
2 answers

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

 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); } } } 
+6
source

I am not an expert on this topic, but I do not understand why this method does not work:

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

One thing about using this approach is that you have to remember that a dummy node is the root of your document. Obviously, you can always simply request the property of the Nodes child nodes to get the necessary information.

+2
source

All Articles