零散的XML字符串使用LINQ解析 [英] Fragmented XML string parsing with Linq
本文介绍了零散的XML字符串使用LINQ解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让我们说我有一个支离破碎的XML如下:
Let's say I have a fragmented XML as follows.
<A>
<B></B>
</A>
<A>
<B></B>
</A>
我可以使用的XmlReader
与片段选项来解析该未完成
XML字符串。
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())
我能做到这一点支离破碎的XML字符串使用LINQ解析?
Can I do this fragmented XML string parsing with Linq?
推荐答案
使用<一个href="http://msdn.microsoft.com/en-us/library/system.xml.linq.xnode.readfrom.aspx"><$c$c>XNode.ReadFrom()$c$c>方法,你可以很容易地创建一个返回 XNode
S的序列的方法:
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);
}
}
}
这篇关于零散的XML字符串使用LINQ解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文