第 11 章 其他 XML 和 JSON 技术 其他 XML 和 JSON 技术
本作品已使用人工智能进行翻译。欢迎您提供反馈和意见:translation-feedback@oreilly.com
在第 10 章中,我们介绍了 LINQ-to-XML API 以及一般的 XML。在本章中,我们将探讨底层的XmlReader/XmlWriter 类以及用于处理 JavaScript Object Notation(JSON)的类型,JSON 已成为 XML 的流行替代品。
在在线补编中,我们介绍了处理 XML 架构和样式表的工具。
XmlReader
XmlReader 是一个高性能类,用于以底层、只向前的方式读取 XML 流。
请看下面的 XML 文件 customer.xml:
<?xml version="1.0" encoding="utf-8" standalone="yes"?> <customer id="123" status="archived"> <firstname>Jim</firstname> <lastname>Bo</lastname> </customer>
要实例化XmlReader ,需要调用静态XmlReader.Create 方法,传入Stream 、TextReader 或 URI 字符串:
using XmlReader reader = XmlReader.Create ("customer.xml");
...
备注
由于XmlReader 允许你从潜在的慢速源(Streams 和 URI)读取数据,因此它提供了大部分方法的异步版本,这样你就可以轻松编写非阻塞代码。我们将在第 14 章详细介绍异步功能。
构建从字符串读取数据的XmlReader :
using XmlReader reader = XmlReader.Create ( new System.IO.StringReader (myString));
您还可以通过XmlReaderSettings 对象来控制解析和验证选项。XmlReaderSettings 上的以下三个属性对于跳过多余内容特别有用:
bool IgnoreComments // Skip over comment nodes? bool IgnoreProcessingInstructions // Skip over processing instructions? bool IgnoreWhitespace // Skip over whitespace?
在下面的示例中,我们指示读者不要发出空白节点,因为在典型的场景中,空白节点会分散读者的注意力:
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreWhitespace = true;
using XmlReader reader = XmlReader.Create ("customer.xml", settings);
...
XmlReaderSettings 的另一个有用属性是ConformanceLevel 。它的默认值Document 会指示阅读器假定一个有效的 XML 文档只有一个根节点。如果只想读取包含多个节点的 XML 内部部分,就会出现问题:
<firstname>Jim</firstname> <lastname>Bo</lastname>
要在读取时不抛出异常,必须将ConformanceLevel
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access