我想阅读 processing instruction来自一些小well-formed XML block ,基于这篇文章: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);”中得到它。
哪里出错了?如何获取/读取处理指令?
最佳答案
您的代码中有两个问题。
首先是它在 Console.WriteLine(doc.ChildNodes[1].Name);
上失败,“root”是第一个节点,而不是第二个(从零开始)。但这可能是一个错字。
关于所讨论的问题:
Enumerable.OfType()正在使用由其父级实现的 XmlDocument
类的 GetEnumerator() XmlNode.GetEnumerator() .文档指出:
An IEnumerator object that can be used to iterate through the child nodes in the current node.
但您正在尝试在 doc 上运行 OfType,他只有一个 child :root。
如果您将代码更改为在 root 的子级上运行,它将按预期工作:
XmlProcessingInstruction pi = doc.ChildNodes[0].OfType<XmlProcessingInstruction>().Where(x => x.Name == "pi").FirstOrDefault();
关于c# - 如何使用 C# .NET 从 XML 字符串中读取处理指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61942462/