XML 解析器,多根
这是输入字符串的一部分,我无法修改它,它总是以这种方式出现(通过共享内存),但我当然可以在将其放入字符串后进行修改:
<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>
我已经用两者读取了它:
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);
但运行时都会出错;输入有多个根(有多个根元素引用),我不想分割字符串。
他们是否有任何方式读取字符串,获取
和 之间的值,而不将字符串吐入多个输入?
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));
and:
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.
Is their any way to read the string take the value between <value>
and </value>
without spiting the string into multiple inputs?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这不是格式良好的 XML 文档,因此大多数 XML 工具无法处理它。
XmlReader
是一个例外。查找XmlReaderSettings.ConformanceLevel
< /a> 在 MSDN 中。如果将其设置为ConformanceLevel.Fragment
,则可以使用这些设置创建一个XmlReader
并使用它从没有顶级元素的流中读取元素。您必须编写使用
XmlReader.Read()
的代码来执行此操作 - 您不能只将其提供给XmlDocument
(这确实要求有一个顶部级元素)。例如,
That's not a well-formed XML document, so most XML tools won't be able to process it.
An exception is the
XmlReader
. Look upXmlReaderSettings.ConformanceLevel
in MSDN. If you set it toConformanceLevel.Fragment
, you can create anXmlReader
with those settings and use it to read elements from a stream that has no top-level element.You have to write code that uses
XmlReader.Read()
to do this - you can't just feed it to anXmlDocument
(which does require that there be a single top-level element).e.g.,
XML 元素必须有一个根元素,可以具有您想要的任何子结构。
您的 xml 字符串如下所示:
有效版本为:
尝试:
XML elements must have ONE root element, with whatever child structure you want.
Your xml string looks like:
The valid version would be:
Try:
此解决方案成功解析所有节点类型,包括文本节点:
跳过 XML 声明,因为它不是节点。
This solution parses successfully all node types, including text nodes:
Skips the XML declaration because it isn't a node.