【发布时间】:2020-09-08 13:16:04
【问题描述】:
我想从一些小的well-formed XML 块中读取processing instruction,基于这篇文章:How to read processing instruction from an XML file using .NET 3.5
但是,它不起作用。我收到错误消息,即 pi 对象为空。 我就是这样做的:
XmlDocument doc = new XmlDocument();
doc.LoadXml("<root>Text <?pi 1?>blabla</root>");
Console.WriteLine(doc.ChildNodes[0].Name); // output: root
XmlProcessingInstruction pi = doc.OfType<XmlProcessingInstruction>().Where(x => x.Name == "pi").FirstOrDefault();
Console.WriteLine(pi.Value);
解析 XML 有效。当我在 Visual Studio 中收到错误 (System-NullReferenceException) 时,我在行“Console.WriteLine(pi.Value);”中得到它。
哪里出错了?如何获取/读取处理指令?
【问题讨论】:
-
这看起来不像是一个有效的 xml。
-
它是格式良好的 XML。是否必须有效才能访问 PI?当我检查 XmlDocument 对象时,它显示了一个成功的解析树。
-
它不是一个有效的 XML,或者至少它不是一个有效的处理指令。试试
doc.LoadXml("<?xml-stylesheet type=\"text/xsl\" href=\"Sample.xsl\"?><Root><Child/></Root>") -
“有效的 XML”和“格式正确的 XML”是有区别的。请参考。 en.wikipedia.org/wiki/Well-formed_document 进行解释。上面的代码使用格式良好的 XML。这没有错。我还尝试更改代码并在开头添加 标记和一个子元素(只是为了确定),但没有更改。您的示例代码也不包含处理指令(参见en.wikipedia.org/wiki/Processing_Instruction)。