System.XML - Enhancement in 2.0 The System.Xml namespace
The System.Xml namespace is to read, write, manipulate, validate, and transform XML – all types possible XML processing are done by this namespace. These are the following goals to enhance the System.Xml 2.0:
Standards compliance:
Support for the major W3C XML standards that provide cross-platform interoperability. System.Xml supports the following standard for processing XML.
1. XML 1.0 - http://www.w3.org/TR/1998/REC-xml-19980210 - including DTD support.
2. XML Namespaces - http://www.w3.org/TR/REC-xml-names/ - both stream level and DOM.
3. XSD Schemas - http://www.w3.org/2001/XMLSchema
4. XPath expressions - http://www.w3.org/TR/xpath
5. XSLT transformations - http://www.w3.org/TR/xslt
6. DOM Level 1 Core - http://www.w3.org/TR/REC-DOM-Level-1/
7. DOM Level 2 Core - http://www.w3.org/TR/DOM-Level-2/
1. Integration with ADO.NET: The System.Xml classes can really be considered part of ADO.NET as an XML data access API. It was a goal to provide a seamless experience when moving between XML and relational data. The DataSet class is the canonical example here.
2. Extensibility: This was achieved through the use of abstract classes to define the XML API and the ability to be able to plug together these classes. The significant abstract classes that provide an extensible model are the XmlReader, the XmlWriter, and the XPathNavigator. The latter is of particular significance since it combines a random access, cursor-style API with an XPath query engine.
3. The V1 design goals above continue to apply in driving the V2.0 release; however, further design goals were added in the V2.0 release around the requirements needed to build a strong set of XML components for the WinFX APIs.
4. Significant Performance Improvement: This was the number one requirement for the V2.0 release. XML is low in the processing stack and performance gains here have a ripple affect through the rest of the application.
5. Usability enhancements: These enhancements make common tasks even easier to do in less lines of code, with support for a greater range of features to broaden the reach and capability of the applications.
6. Querying Data Sources: This is standards support for the W3C XQuery language for querying XML, with the ability to aggregate data from different data sources such as SQL Server databases and local XML files.
7. Enhanced XML Schema Support and Typing: This provides a set of XML type-aware APIs. Virtually every XML API that ships today is untyped in that the data is both stored and surfaced only as string types (such as the DOM API). Integrating schema information deeply across the System.Xml APIs not only provides support for type-aware query languages such as XQuery, but provides for more efficient storage, improved performance, and better integration with the .NET programming languages.
New Features of Symtem.Xml 2.0
The followings are the features of System.Xml 2.0
1. New Enhanced XML Data Processing Model: In-memory XML data processing model is new. Using XPathNavigator combining with XmlDocument class XML Document can be modified.
2. New XSLT Processor: The XslTransform class of System.Xml.Xsl namespace is used which is based on MSXML 3.0 XSLT Processor. In .NET framework 2.0 the XSLT architecture is redesigned which is based on MSXML 4.0 XSLT Processor. The new XSLT processor, XslCompiledTransform class includes many performance improvements and optimizations.
3. Type Support: New methods of XmlReader, XmlWriter, and XPathNavigator classes can return a node value as a common language runtime object. Type support features including the ability to convert between XML Schema types and common language runtime (CLR) types.
4. New Model for Creating XmlReader and XmlWriter Objects: Instead of creating concrete object, the static Create methods on the XmlReader and XmlWriter classes are the recommended for creating XmlReader and XmlWriter objects. By using the Create method and the XmlReaderSettings class you able to specify which features you want supported and XmlReaderSettings class can be reused to create multiple reader objects.
5. Schema Inference: The class XmlSchemaInference class allows you to infer an XML Schema definition language (XSD) schema from the structure of an XML document.
Processing XML Documents using non-cached method
The XmlReader class provides non-cached, forward-only, read-only access to XML data. The XmlReader class supports reading XML data from a stream or file. The XmlReader class provides the following features:
· Validates legal XML characters and that element and attribute names.
· Checks that the XML document is well formed.
· Validates the data against a DTD or schema.
· Retrieves data from the XML stream or skip unwanted records using a pull model.
The most important features for reading and in System.Xml 2.0 XmlReaderSettings and XmlWriterSettings are the two classes have been introduced used as a "factory" which is used to simplify the reading / writing XML document.
Same instance of this factory class is used multiple times and the setting of this changed for each cases. Thus the process reduces the code.
The code as well as the performance can be optimized for the case of multiple times using the same instance of the XmlReaderSettings / XmlWriterSettings object changing / setting only the required properties.
This factory classes provides features like as reading or ignoring DTDs, schemas, white-space, comments, validating for XML documents or fragments of XML, control access to resources, add credentials for accessing remote or secured.
Another major improvement of 2.0, the XmlReader and XmlWriter classes are having new Static/Shared method which allows creating instances by specifying an XmlReaderSettings or XmlWriterSettings class instance that defines the behaviour.
In .NET Framework 1.x concrete implementations through XmlTextReader, XmlNodeReader, and the XmlValidatingReader classes inheriting from XmlReader for reading operation of XML file, but in 2.0 it is recommended to do this job creating XmlReader instances using the Create method.
To handle errors or exceptions such as security exception or if the XML file or stream, use a Try..Catch for creating the XmlReader object.
Reading XML using XmlReader & XmlReaderSetting Class
The steps to read XML using XmlReader and XmlReaderSettings classes are as follows:
i. Instantiate an instance of the XmlReaderSettings class
XmlReaderSettings readerSettings = new XmlReaderSettings();
ii. Set the properties on XmlReaderSettings object those are required.
readerSettings.IgnoreWhitespace = true;
iii. Call the Create method of the XmlReader class.
XmlReader reader = XmlReader.Create(@"../../Customers.xml", readerSettings)
Highlights of the following example
1. We have created the XmlReaderSettings object and assigned the properties.
2. XmlReader instance is created by Create static / Shared funtion.
3. We read two separate XML files using only one XmlReaderSettings
The code of ReadingXmlUsingXmlReader.aspx.cs file is as follows.
using System;
using System.Xml;
namespace ReadingUsingXmlReader
{
class ReadingFromXmlFile
{
static void Main()
{
XmlReaderSettings readerSettings = new XmlReaderSettings();
//Ignore insignificant white space.
readerSettings.IgnoreWhitespace = true;
//Ignore comments.
readerSettings.IgnoreComments = true;
//Check the XML names and text content are valid
readerSettings.CheckCharacters = true;
//The underlying stream or TextReader should be closed
//when the reader is closed.
readerSettings.CloseInput = true;
//Ignore processing instructions.
readerSettings.IgnoreProcessingInstructions = false;
//Indicates the schema validation settings.
//This setting applies to schema validating XmlReader objects
//(ValidationType property set to ValidationType.Schema).
readerSettings.ValidationFlags =
System.Xml.Schema.XmlSchemaValidationFlags.None;
//Indicating whether the XmlReader will perform
//validation or type assignment when reading.
readerSettings.ValidationType = ValidationType.None;
using (XmlReader reader = XmlReader.Create(@"../../Customers.xml", readerSettings))
{
while (!reader.EOF)
{
if (reader.IsStartElement("CompanyName"))
{
string CompanyName = "";
try
{
CompanyName = reader.ReadInnerXml();
}
catch (Exception)
{
CompanyName = "Error Reading Company Name";
}
Console.WriteLine("Company Name: " + CompanyName);
Console.WriteLine("");
}
else
{
reader.Read();
}
}
}
Console.WriteLine();
Console.WriteLine("Press Enter");
Console.ReadLine();
using (XmlReader reader = XmlReader.Create(@"../../Books.xml", readerSettings))
{
while (!reader.EOF)
{
if (reader.IsStartElement("price"))
{
double price = 0.0;
try
{
//10% Discount: Data is extracted as double
price = reader.ReadElementContentAsDouble() * 0.9;
}
catch (Exception)
{
price = 0.0;
}
Console.WriteLine("Price : " + price.ToString());
Console.WriteLine("");
}
else
{
reader.Read();
}
}
}
Console.WriteLine();
Console.WriteLine("Press Enter to Exit");
Console.ReadLine();
}
}
}
.
Different properties of XmlReaderSettings Class
Features can enabled or disabled by setting the properties on the XmlReaderSettings class, then XmlReaderSettings object is then passed to the Create method.
The following main settings are supported by the XmlReaderSettings
Property | Description |
CheckCharacters | Whether to check the XML names and text content are valid. |
CloseInput | Whether the underlying stream or TextReader should be closed when the reader is closed. |
ConformanceLevel | This property provides the support to read the fragmented file or document. |
IgnoreComments | Whether to ignore comments. |
IgnoreProcessingInstructions | Whether to ignore processing instructions. |
IgnoreWhitespace | Whether to ignore insignificant white space. |
ProhibitDtd | Whether to prohibit document type definition (DTD) processing. |
Schemas | To use when performing schema validation. |
ValidationFlags | Indicates the schema validation settings. This setting applies to schema validating XmlReader objects (ValidationType property set to ValidationType.Schema). |
ValidationType | Indicating whether the XmlReader will perform validation or type assignment when reading. |
XmlResolver | Sets the XmlResolver used to access external documents. |
Reading Fragmented XML
The fragmented XML which is not strictly well-formed using XmlReader.
Steps 1
The ConformanceLevel property of the XmlReaderSettings instance has to ConformanceLevel.Fragment before creating the XmlReader for reading fragmented XML..
// Create the reader settings.
XmlReaderSettings settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Fragment;
Step 2
XML fragments may not contain the required namespace declarations, or the <?xml ...?> declaration etc. The information required to it, isn’t sufficient. Therefore the missing information is provided by creating and populating an appropriate XmlParserContext instance.
Adding a new NameTable to hold the namespace declarations to the XmlReaderSettings and then creating a new XmlNamespaceManager over this. Then add the required namespaces to the XmlNamespaceManager.
// Create the XmlNamespaceManager.
NameTable nt = new NameTable();
XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);
nsmgr.AddNamespace("rk", "urn:store-items");
Step 3
Create an instance of XmlParserContext using the XmlNamespaceManager.
// Create the XmlParserContext.
XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None);
Step 4
Create the XmlReader instance using Create method passing an XmlReaderSettings and XmlParserContext instance.
XmlReader reader = XmlReader.Create(new StringReader(xmlFrag), settings, context);
Validating XML
The XmlValidatingReader class is obsolete in the .NET Framework 2.0 release.
The ConformanceLevel property of the XmlReaderSettings instance has to ConformanceLevel.Fragment before creating the XmlReader for reading fragmented XML.
// Create the reader settings.
XmlReaderSettings settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Fragment;
ValidationType and ValidationFlags properties of XmlReaderSettings class are used for validating XML.
DTD
To validate XML document using a document type definition (DTD), the ProhibitDtd property has to set to false and ValidationType.DTD is DTD enumeration type.
ProhibitDtd = false
ValidationType = ValidationType.DTD
Schema
To validate XML document using an XML Schema definition language (XSD) schema, ValidationType will be ValidationType.Schema.
ValidationType = ValidationType.Schema
To validate an XML document using the schemas, Scchemas property has to set XmlSchemaSet.
Schemas = XmlSchemaSet to use for validation
For the case of validating using the in-line schema contained in the XML instance document, ValidationFlags has to set XmlSchemaValidationFlags.ProcessInlineSchema (The ProcessInlineSchema option must be enabled.)
ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema
None
The XmlReader does not validate data, or perform any type assignment.
using System;
using System.Xml;
using System.Xml.Schema;
using System.IO;
namespace SyestemXml2
{
class ValidatingXml
{
static void Main(string[] args)
{
// Create the XmlSchemaSet class.
XmlSchemaSet sc = new XmlSchemaSet();
// Add the schema to the collection.
sc.Add("urn:bookstore-schema", @"../../books.xsd");
// Set the validation settings.
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas = sc;
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
// Create the XmlReader object.
XmlReader reader = XmlReader.Create(@"../../booksSchemaFail.xml", settings);
// Parse the file.
while (reader.Read()) ;
Console.Read();
}
// Display any validation errors.
private static void ValidationCallBack(object sender, ValidationEventArgs e)
{
Console.WriteLine("Validation Error: {0}", e.Message);
}
}
}
The source of books.xsd
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="urn:bookstore-schema"
elementFormDefault="qualified"
targetNamespace="urn:bookstore-schema">
<xsd:element name="bookstore" type="bookstoreType"/>
<xsd:complexType name="bookstoreType">
<xsd:sequence maxOccurs="unbounded">
<xsd:element name="book" type="bookType"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="bookType">
<xsd:sequence>
<xsd:element name="title" type="xsd:string"/>
<xsd:element name="author" type="authorName"/>
<xsd:element name="price" type="xsd:decimal"/>
</xsd:sequence>
<xsd:attribute name="genre" type="xsd:string"/>
</xsd:complexType>
<xsd:complexType name="authorName">
<xsd:sequence>
<xsd:element name="first-name" type="xsd:string"/>
<xsd:element name="last-name" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
The source of booksSchemaFail.xml
<?xml version='1.0'?>
<bookstore xmlns="urn:bookstore-schema">
<book>
<author>
<first-name>Scott</first-name>
<last-name>John</last-name>
</author>
</book>
<book genre="tech">
<title>Dontnet 2.0</title>
<author>
<first-name>Steve</first-name>
<last-name>Ray</last-name>
</author>
<price>7.8</price>
</book>
<book genre="computer">
<title>XML</title>
<author>
<name>Chis</name>
</author>
<price>45.25</price>
</book>
</bookstore>