XML解析器,多个根 [英] XML parser, multiple roots
问题描述
这是输入字符串的一部分,我不能修改它,它总是以这种方式(通过共享内存)来实现,但是我当然可以在将其放入字符串后进行修改:
This is part of the input string, i can't modify it, it will always come in this way(via shared memory), but i can modify after i have put it into a string of course:
<sys><id>SCPUCLK</id><label>CPU Clock</label><value>2930</value></sys><sys><id>SCPUMUL</id><label>CPU Multiplier</label><value>11.0</value></sys><sys><id>SCPUFSB</id><label>CPU FSB</label><value>266</value></sys>
我同时阅读了以下内容:
i've read it with both:
String.Concat(
XElement.Parse(encoding.GetString(bytes))
.Descendants("value")
.Select(v => v.Value));
和:
XmlDocument document = new XmlDocument();
document.LoadXml(encoding.GetString(bytes));
XmlNode node = document.DocumentElement.SelectSingleNode("//value");
Console.WriteLine("node = " + node);
,但是它们在运行时都有错误;输入有多个根(有多个根元素引用),我不想拆分字符串。
but they both have an error when run; that the input has multiple roots(There are multiple root elements quote), i don't want to have to split the string.
它们是读取字符串的任何方式是否在< value>
和< / value>
之间的值不将字符串吐入多个输入? p>
Is their any way to read the string take the value between <value>
and </value>
without spiting the string into multiple inputs?
推荐答案
这不是格式正确的XML文档,因此大多数XML工具将无法对其进行处理。
That's not a well-formed XML document, so most XML tools won't be able to process it.
XmlReader
是一个例外。查找 XmlReaderSettings.ConformanceLevel
在MSDN中。如果将其设置为 ConformanceLevel.Fragment
,则可以使用这些设置创建 XmlReader
并使用它从中读取元素
An exception is the XmlReader
. Look up XmlReaderSettings.ConformanceLevel
in MSDN. If you set it to ConformanceLevel.Fragment
, you can create an XmlReader
with those settings and use it to read elements from a stream that has no top-level element.
您必须编写使用 XmlReader.Read()
的代码为此,您不能仅将其提供给 XmlDocument
(确实需要有一个顶级元素)。
You have to write code that uses XmlReader.Read()
to do this - you can't just feed it to an XmlDocument
(which does require that there be a single top-level element).
例如
var readerSettings = new XmlReaderSettings { ConformanceLevel = ConformanceLevel.Fragment };
using (var reader = XmlReader.Create(stream, readerSettings))
{
while (reader.Read())
{
using (var fragmentReader = reader.ReadSubtree())
{
if (fragmentReader.Read())
{
var fragment = XNode.ReadFrom(fragmentReader) as XElement;
// do something with fragment
}
}
}
}
这篇关于XML解析器,多个根的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!