简体   繁体   English

使用 Linq 解析的分段 XML 字符串

[英]Fragmented XML string parsing with Linq

Let's say I have a fragmented XML as follows.假设我有一个碎片 XML 如下。

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

I can use XmlReader with Fragment option to parse this not complete XML string.我可以使用带有 Fragment 选项的XmlReader来解析这个not complete的 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())

Can I do this fragmented XML string parsing with Linq?我可以用 Linq 做这个零碎的 XML 字符串解析吗?

Using the XNode.ReadFrom() method , you can easily create a method that returns a sequence of XNode s:使用XNode.ReadFrom()方法,您可以轻松创建一个返回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);
        }
    }
}

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.显然,您总是可以只查询子节点属性来获取您需要的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM