Chapter 11. Other XML and JSON Technologies
In Chapter 10, we covered the LINQ-to-XML API—and XML in general. In this chapter, we explore the low-level XmlReader
/XmlWriter
classes and the types for working with JavaScript Object Notation (JSON), which has become a popular alternative to XML.
In the online supplement, we describe the tools for working with XML schema and stylesheets.
XmlReader
XmlReader
is a high-performance class for reading an XML stream in a low-level, forward-only manner.
Consider the following XML file, customer.xml:
<?xml version="1.0" encoding="utf-8" standalone="yes"?> <customer id="123" status="archived"> <firstname>Jim</firstname> <lastname>Bo</lastname> </customer>
To instantiate an XmlReader
, you call the static XmlReader.Create
method, passing in a Stream
, a TextReader
, or a URI string:
using XmlReader reader = XmlReader.Create ("customer.xml"); ...
Note
Because XmlReader
lets you read from potentially slow sources (Stream
s and URIs), it offers asynchronous versions of most of its methods so that you can easily write nonblocking code. We cover asynchrony in detail in Chapter 14.
To construct an XmlReader
that reads from a string:
using XmlReader reader = XmlReader.Create ( new System.IO.StringReader (myString));
You can also pass in an XmlReaderSettings
object to control parsing and validation options. The following three properties on XmlReaderSettings
are particularly useful for skipping over superfluous content:
bool IgnoreComments // Skip over ...
Get C# 12 in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.