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 t开发者_如何学Chis 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?
Using the XNode.ReadFrom()
method, you can easily create a method that returns a sequence of XNode
s:
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);
}
}
}
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.
精彩评论