c# – 使用Linq进行分段的XML字符串解析

假设我有一个支离破碎的XML,如下所示.

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

我可以使用XmlReader with Fragment选项来解析这个不完整的XML字符串.

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

我可以使用Linq进行碎片化的XML字符串解析吗?

最佳答案
使用XNode.ReadFrom() method,您可以轻松创建一个返回一系列XNode的方法:

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

转载注明原文:c# – 使用Linq进行分段的XML字符串解析 - 代码日志