Microsoft KB Archive/330589

= HOW TO: Implement Common MSXML Tasks in System.xml By Using Visual C# .NET =

Article ID: 330589

Article Last Modified on 8/4/2004

-

APPLIES TO


 * Microsoft .NET Framework Class Libraries 1.1
 * Microsoft .NET Framework Class Libraries 1.0
 * Microsoft Visual C# .NET 2003 Standard Edition
 * Microsoft Visual C# .NET 2002 Standard Edition
 * Microsoft XML Core Services 4.0
 * Microsoft Visual Basic 6.0 Enterprise Edition

-



This article was previously published under Q330589



This article refers to the following Microsoft .NET Framework Class Library namespaces:
 * System.Xml
 * System.Xml.Xsl
 * System.Xml.XPath
 * System.Net

IN THIS TASK
 * SUMMARY
 * REQUIREMENTS
 * MSXML vs. System.xml for XML Processing
 * Load, Access, Manipulate and Save XML Documents
 * Parsing or Validating XML Documents
 * Apply XSLT Transformation on XML Document
 * Sending Requests from and Parsing Responses into the XML Document
 * REFERENCES



SUMMARY
This step-by-step article describes the features of MSXML and .NET Framework Classes for XML processing. This article also includes samples on how to use MSXML in Microsoft Visual Basic 6.0 and how to use .NET Framework Classes for XML processing.
 * Microsoft XML Core Services (MSXML)

Using MSXML, you can build XML-based applications. You can easily use MSXML in Visual Studio 6.0 applications as DOM and SAX Parser with support for XSLT and XPath.
 * .NET Framework Classes for XML

The System.Xml namespace provides standards-based support for processing XML. System.xml is not just the managed version of MSXML; its functionality may overlap that of the MSXML COM library, and it also contains a rich object model and hierarchy.

For additional information, visit the following Microsoft Web site:

Design Goals for XML in the .NET Framework

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpcondesigngoalsforxmlframeworkinnet.asp

back to the top



REQUIREMENTS
 Microsoft XML Core Services (MSXML) 4.0 Software Development Kit (SDK)

Note: To perform XML Schema validations using MSXML, you must have MSXML 4.0. Make sure that the MSXML 4.0 SDK is installed on your computer before you run the code sample in the Parsing or Validating XML Documents section of this article. All the remaining samples also work with MXSML 3.0.

To download the MSXML 4.0 SDK, visit the the following Microsoft Web site:

http://download.microsoft.com/download/xml/SP/40SP1/WIN98MeXP/EN-US/msxml.msi

 Use Microsoft Visual Basic 6.0 for MSXML samples. Add a reference to Microsoft XML version 4.0 or Microsoft XML version 3.0.  All the samples in this article refers to the following XML document. Make sure to copy this document to the C:\XMLMigration directory.Books.xml    Pride And Prejudice 24.95  The New Dawn 29.95    Blue Smoke 19.95 </ul>

back to the top

<div class="moreinformation_section">

MSXML vs. System.xml for XML Processing
The following are the comparisons to consider when you migrate from MSXML 4.0 to .NET Framework classes for XML.

Simple API for XML (SAX)
<ul> ===== MSXML =====

The SAX event-based model is the most resource-efficient and high-performance way of using MSXML. </li> ===== .NET Framework Classes =====

Instead, XmlReader and XmlWriter are the abstract classes that implement the API for reading and writing data. The XmlReader is a pull model parser and has several advantages over the SAX push model, such as state management, selective processing, layering, and Extra String Copy Avoidance. </li></ul>

XSL Transformation
<ul> ===== MSXML =====

Using the Transform method of an XSLProcessor object, you can apply a style sheet to a document. There is also a transformNode method that applies a style sheet to a specified node and its children. </li> ===== .NET Framework Classes =====

The XSLT recommendation uses XPath to select parts of an XML document, where XPath is a query language used to navigate the nodes of a document tree. XPathDocument is an optimized XSLT data store. When XPathDocument is used with XslTransform, the performance of XSLT transformations improve. </li></ul>

XML Validations
<ul> ===== MSXML =====

You can validate XML with the XML schema in both SAX and DOM. Although there is no XPath 2.0, MSXML 4.0 provides extension functions that are permitted by the standards to support the handling of XSD types in XPath and XSLT. In addition to the support for the final XML Schema recommendation, MSXML continues to support XML-Data Reduced (XDR) and the document type definition (DTD) validations. </li> ===== .NET Framework Classes =====

The XmlValidatingReader is a XML-compliant parser. The XmlSchemaCollection class can be used to cache frequently used XSD or XDR schemas when using XmlValidatingReader. </li></ul>

XML Navigation
<ul> ===== MSXML =====

It also provides basic facilities for manipulating strings, numbers, and Booleans. XPath uses a compact, non-XML syntax to make it easier to use XPath in URIs and XML attribute values. XPath is named based on the path notation that it uses in URLs to explore the hierarchical structure of an XML document. </li> ===== .NET Framework Classes =====

In this navigation style, a complete node tree is not to be built in memory. </li></ul>

Accessing Data Over HTTP
<ul> ===== MSXML =====

When combined with the support for Extensible Stylesheet Language (XSL), the XMLHTTP component provides an easy way to send structured queries to HTTP servers and displays the results with a variety of presentations. </li> ===== .NET Framework Classes =====

The HttpWebRequest and HttpWebResponse classes in the System.net namespace provide the functionality of XMLHTTP in the .NET framework. Using the ContentType property, you can specify the media type of the request. </li></ul>

back to the top

<div class="moreinformation_section">

Load, Access, Manipulate, and Save XML Documents
The following code example narrates how to load and save the XML documents. The sample also includes how to append, delete, and update the elements in XML documents.

Using MSXML
Note: To run the following MSXML sample code, see the &quot;Requirements&quot; section in this article: On Error GoTo Handle

'Create the XmlDocument.

Dim objDOMDoc As New DOMDocument30 objDOMDoc.async = False objDOMDoc.Load (&quot;C:\XMLMigration\books.xml&quot;) Debug.Print (&quot;\n XML Document Loaded&quot;)

' Set the root element. Dim root As MSXML2.IXMLDOMElement Set root = objDOMDoc.documentElement ' Select and display the value of all the publicationdate attributes. Debug.Print (&quot;\n List of Publications&quot;) Dim pbDateList As MSXML2.IXMLDOMNodeList Set pbDateList = root.selectNodes(&quot;/bookstore/book/@publicationdate&quot;) Dim nameList As MSXML2.IXMLDOMNodeList Set nameList = root.selectNodes(&quot;/bookstore/book/title&quot;)

Dim i As Integer For i = 0 To nameList.length - 1 Step i + 1 Debug.Print (&quot;\n\t\tName: &quot; + nameList(i).Text + &quot;,Published :&quot; + pbDateList(i).Text) Next

'Select the book node with the matching attribute value. Dim book As MSXML2.IXMLDOMNode, price As MSXML2.IXMLDOMNode Set book = root.selectSingleNode(&quot;book[@bk:ISBN='1-861001-57-6']&quot;)

' Selects the first 'Price' element and modify its value. Set price = book.selectSingleNode(&quot;price&quot;) price.Text = &quot;50.5&quot; Debug.Print (&quot;\n First Book Price Updated&quot;)

' Remove the last element. root.removeChild root.lastChild Debug.Print (&quot;\n Last Element Deleted&quot;)

'Create a new node. Dim elem As MSXML2.IXMLDOMElement Set elem = objDOMDoc.createElement(&quot;book&quot;) elem.setAttribute &quot;genre&quot;, &quot;novel&quot; elem.setAttribute &quot;publicationdate&quot;, &quot;1982&quot;

' Attribute to the root namespace (another namespace) Dim objAttribNode As MSXML2.IXMLDOMNode Set objAttribNode = objDOMDoc.createNode(2, &quot;bk:ISBN&quot;, &quot;urn:samples&quot;) objAttribNode.nodeTypedValue = &quot;1-851002-30-1&quot; elem.Attributes.setNamedItem objAttribNode

'Add the node to the document. root.appendChild elem Debug.Print (&quot;\n Element appended to XML Document&quot;) objDOMDoc.save (&quot;C:\XMLMigration\books.xml&quot;) Debug.Print (&quot;\n XML Document Saved&quot;) Exit Sub

Handle: Debug.Print (&quot;Error: &quot; + Err.Description)

Using .NET Framework Classes
using System; using System.Xml;

public class CSharpSample {   public static void Main {       //Create the XmlDocument. Console.Write (&quot;\n .NET Framework Sample\n&quot;); XmlDocument doc = new XmlDocument; doc.Load(@&quot;C:\XMLMigration\books.xml&quot;);

//Create an XmlNamespaceManager for resolving namespaces. XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); nsmgr.AddNamespace(&quot;bk&quot;,&quot;urn:samples&quot;); XmlNode book,price; XmlElement root = doc.DocumentElement;

// Select and display the value of all the publicationdate attributes. Console.Write (&quot;\n List of Publications\n&quot;); XmlNodeList pbDateList = root.SelectNodes(&quot;/bookstore/book/@publicationdate&quot;); XmlNodeList nameList = root.SelectNodes(&quot;/bookstore/book/title&quot;); for(int i=0;i < nameList.Count ;i++) Console.WriteLine(&quot;\n\t\tName: &quot; + nameList[i].InnerText + &quot;,Published :&quot; + pbDateList[i].InnerText);

//Select the book node with the matching attribute value. book = root.SelectSingleNode(&quot;descendant::book[@bk:ISBN='1-861001-57-6']&quot;, nsmgr); // Selects the first 'Price' element and modify its value. price = book.SelectSingleNode(&quot;price&quot;); price.InnerText = &quot;50.5&quot;; Console.Write (&quot;\n First Book Price Updated&quot;);

// Remove the first element. root.RemoveChild(root.LastChild); Console.Write (&quot;\n Last Element Deleted&quot;);

// Create a new node and set its attributes. XmlElement elem = doc.CreateElement(&quot;book&quot;); elem.SetAttribute(&quot;genre&quot;,&quot;novel&quot;); elem.SetAttribute(&quot;publicationdate&quot;,&quot;1982&quot;); elem.SetAttribute(&quot;ISBN&quot;,&quot;urn:samples&quot;,&quot;1-851002-30-1&quot;);

//Add the node to the document and save the XML. root.AppendChild(elem); Console.Write (&quot;\n Element appended to XML Document&quot;); doc.Save(@&quot;C:\XMLMigration\books.xml&quot;); Console.Write (&quot;\n XML Document Saved&quot;);

Console.ReadLine;

} }

Using XPathDocument for Read-only XPath Queries
To perform XPath queries in read-only mode, Microsoft recommends that you use the System.Xml.XPath.XPathDocument class. The following example describes how to use XPathDocument class to execute the XPath queries. using System; using System.Xml; using System.Xml.XPath;

public class XPATHDOC {   public static void Main {       // Creating XPathDocument and XPathNavigator. XPathDocument doc = new XPathDocument(@&quot;C:\XMLMigration\books.xml&quot;); XPathNavigator nav = doc.CreateNavigator;

// Creating XPathExpression to select all the novels XPathExpression expression = nav.Compile(&quot;descendant::book[@genre='novel']&quot;); XPathNodeIterator nodeIterator = nav.Select(expression);

while (nodeIterator.MoveNext) {          XPathNavigator nav2 =   nodeIterator.Current; Console.Write(&quot;\n\t Book Title & Price : &quot; + nav2.Value); nav2.MoveToNext; }              } } Back to the top

<div class="moreinformation_section">

Parsing or Validating XML Documents
You can validate an XML document against an XML Schema definition language (XSD) schema document. To generate the Books.xsd schema file for the XML file Books.xml, use the XML Schema Definition Tool (Xsd.exe). To do this, follow these steps:
 * 1) On the Visual Studio .NET Tools menu, open the Visual Studio .NET command prompt.
 * 2) Change the directory to C:\XMLMigration\
 * 3) Type the following at command line: xsd.exe books.xml
 * 4) Notice that the following list of files is generated in this folder:
 * 5) * Books.xsd
 * 6) * Books_app1.xsd

The following code examples demonstrate how to perform validation on books.xml using MSXML and .NET Framework classes.

Using MSXML

 * 1) This code creates an XMLSchemaCache40 object, adds the schema (books.xsd) to the object, and then refers the schema of the DOMDocument object
 * 2) Validation is performed when the books.xml file is loaded onto the DOMDocument object.
 * 3) Validation errors are returned using the parseError property of the DOMDocument object.

Note: To run the following MSXML sample code, see the &quot;Requirements&quot; section in this article. On Error GoTo Handle ' Create a schema cache and add books.xsd to it. Dim xmlschema As New MSXML2.XMLSchemaCache40 xmlschema.Add &quot;&quot;, &quot;C:\XmlMigration\books.xsd&quot; ' Create an XML DOMDocument object. Dim xmldom As New MSXML2.DOMDocument40 ' Assign the schema cache to the DOM document, schemas collection. Set xmldom.schemas = xmlschema

' Load books.xml as the DOM document. xmldom.async = False xmldom.Load (&quot;C:\XMLMigration\books.xml&quot;)

' Return validation results in message to the user. If xmldom.parseError.errorCode <> 0 Then Debug.Print (xmldom.parseError.errorCode + xmldom.parseError.reason) Else Debug.Print (&quot;No Validation Errors&quot;) End If Exit Sub Handle: Debug.Print (&quot;Validation Errors &quot; + Err.Description)

Using .NET Framework Classes
The .NET Framework provides the XmlValidatingReader class for validating XML Documents. To validate a XML document using XSD schema, follow these steps:
 * 1) Create a Validating reader object.
 * 2) Specify the type of validation required.
 * 3) Register a event handler method, to deal with validation errors.
 * 4) Read and validate the document.
 * 5) Provide an implementation for the validation event handler method.

using System; using System.Xml; using System.Xml.Schema; using System.IO;

public class CSharpSchemaValidation {   private static string validationErrors = String.Empty; // the ValidationCallBack method is called when a Validation error occurs public static void ValidationCallBack(object sender, ValidationEventArgs e)    { validationErrors += e.Message + &quot;;&quot;; }

public static void Main {       try {           // looking for the element tags. string nodeNames = String.Empty; // Read the xml file, and send this to validator. XmlTextReader xmlReader = new XmlTextReader(@&quot;C:\XMLMigration\books.xml&quot;);

// load the schema file into an XmlTextReader object XmlTextReader xsdReader = new XmlTextReader(@&quot;C:\XMLMigration\books.xsd&quot;); XmlSchemaCollection sc = new XmlSchemaCollection; // add the ValidationEventHandler to the schema collection sc.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack); // add the schema to the XmlSchemaCollection object sc.Add(&quot;&quot;, xsdReader); // create an XmlValidatingReader object based on the Xml document XmlValidatingReader rdr = new XmlValidatingReader(xmlReader); // set the ValidationType to a schema rdr.ValidationType = ValidationType.Schema; rdr.Schemas.Add(sc); rdr.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack); while (rdr.Read) {               if (rdr.NodeType == XmlNodeType.Element) nodeNames += rdr.Name + &quot; &quot;; }           if (validationErrors != String.Empty) {               // errors were added during the ValidationEventHandler char[] delimiter = new Char[1]; delimiter[0] = Convert.ToChar(&quot;;&quot;); string[] errors = validationErrors.Split(delimiter); for(int i=0; i<errors.Length; i++) Console.WriteLine(errors[i]); }           else {               // there were no validation errors, so display that message, or use the 'nodeNames' Console.WriteLine(&quot;No validation errors.&quot;); }       }        catch (Exception ex) {           validationErrors += ex.Message + &quot;;&quot;; Console.WriteLine( validationErrors); }   } } back to the top

<div class="moreinformation_section">

XSLT Transformation
The following example uses Books.xsl to perform the XSLT Transformation on Books.xml: <?xml version='1.0'?> <xsl:stylesheet version=&quot;1.0&quot; xmlns:xsl=&quot;http://www.w3.org/1999/XSL/Transform&quot;> <xsl:template match=&quot;bookstore&quot;> </xsl:template> <xsl:template match=&quot;book&quot;> <TR> <xsl:apply-templates select=&quot;*&quot; /> </TR> </xsl:template> <xsl:template match=&quot;title&quot;> <TD> <xsl:value-of select=&quot;.&quot;/> </TD> </xsl:template> <xsl:template match=&quot;price&quot;> <TD> <xsl:value-of select=&quot;.&quot;/> </TD> </xsl:template> </xsl:stylesheet>

Using MSXML

 * 1) Synchronously load the XSLT style sheet onto a FreeThreadedDOMDocument object
 * 2) Create an instance of an XSLTemplate object.
 * 3) Set the style sheet property of the XSLTemplate object to the FreeThreadedDocument object containing the XSLT stylesheet.
 * 4) Assign the source XML node to the input property of the XSLProcessor object.
 * 5) Invoke the transformation by calling the transform method of the XSLProcessor object.
 * 6) Obtain the results of transformation from the output property of the XSLProcessor object.

Note: To run the following MSXML sample code, see the &quot;Requirements&quot; section in this article:

On Error GoTo Handle ' Create FreeThreadedDOMDocument Dim oXSLT As New MSXML2.XSLTemplate Dim oStyleSheet As New MSXML2.FreeThreadedDOMDocument Dim oXSLTProc As MSXML2.IXSLProcessor Dim oXMLSource As New MSXML2.DOMDocument30

' Load the XSLT Stylesheet oStyleSheet.async = False oStyleSheet.Load (&quot;C:\XMLMigration\books.xsl&quot;)

' Create the XSLTemplate object Set oXSLT.stylesheet = oStyleSheet

' Create the XSLProcessor object; Set oXSLTProc = oXSLT.createProcessor

' Load XML source in DOMDocument oXMLSource.async = False oXMLSource.Load (&quot;C:\XMLMigration\books.xml&quot;)

' Add a global paramter. oXSLTProc.addParameter &quot;TableOnly&quot;, &quot;Yes&quot;, &quot;&quot;

' Assign XML source to XSLProcessor object oXSLTProc.input = oXMLSource

' Invoke the transformation oXSLTProc.Transform

' Use output of transformation. Debug.Print (oXSLTProc.output) Exit Sub Handle: Debug.Print (&quot;Error : &quot; & Err.Description)

Using .NET Framework Classes
To use XSLTransform in the .NET Framework, follow these steps:
 * 1) Create an instance of an XSLTransform object.
 * 2) Using the Load method, load an XSLT style sheet in the XSLTransform object.
 * 3) Using the Transform method, invoke the transformation by providing the source XPathDocument and the target output.

using System; using System.IO; using System.Xml; using System.Xml.Xsl; using System.Xml.XPath;

public class NETXSL {   public static void Main {       //Load the xml file into XPathDocument object. XPathDocument doc = new XPathDocument(@&quot;C:\XMLMigration\books.xml&quot;); //Create the XslTransform object. XslTransform xslt = new XslTransform;

//Load the stylesheet. xslt.Load(@&quot;c:\temp\books.xsl&quot;); FileStream stream = File.Open(@&quot;C:\XMLMigration\books.html&quot;, FileMode.OpenOrCreate); xslt.Transform(doc, null, stream); } }

back to the top

<div class="moreinformation_section">

Execute HTTP Request
The following code example demonstrates how to make a request to a Web server, and receive response from that Web server:

Using MSXML Component
<ol> Create an instance of an XMLHttp object.</li> Call the open method, set HTTP parameters optionally, such as method type, URL ,custom headers or other credentials.</li> Invoke the send method to make an HTTP request.</li> Check the response from the server by the following properties: <ul> responseBody: returns response in an array of unsigned bytes</li> responseStream: returns response in a stream.</li> <li>responseText: returns response as a string.</li> <li> responseXML: returns response as DOMDocument of the XML.

Note: To run the following MSXML sample code, see the &quot;Requirements&quot; section in this article: Dim oXMLHttpRequest As New MSXML2.XMLHTTP ' Change the Microsoft Internet Information Server (IIS) name in following URL. oXMLHttpRequest.open &quot;GET&quot;, &quot;http://[servername]/[virtualdirectory]/[filename.xml]&quot;, False, &quot;&quot;, &quot;&quot; oXMLHttpRequest.send Debug.Print (oXMLHttpRequest.responseText) </li></ul> </li></ol>

Using Microsoft .NET Framework Classes

 * 1) Create an instance of an HttpWebRequest object by calling the static Create method of the WebRequest class.
 * 2) Optionally, set HTTP request attributes, such as method type, custom headers or other credentials.
 * 3) Call the GetResponse method of the HttpWebRequest object. This returns an HttpWebResponse object.
 * 4) Invoke the GetResponseStream method of the HttpWebResponse object to capture the body of the response.
 * 5) Call the Close method of the HttpWebResponse object to release the connection.

using System; using System.Xml; using System.Net; public class CSharpHttpExample {       public static void Main {           // Change the Microsoft Internet Information Server (IIS) name in following URL. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(&quot;http://[ServerName]/[virtualdir]/[filename.xml]&quot;);

// Change Username and password. request.Credentials = new NetworkCredential(&quot;[username]&quot;, &quot;[password]&quot;);

// Downloads the XML file from the specified server. HttpWebResponse response = (HttpWebResponse)request.GetResponse; // Loads the XmlDocument. XmlDocument doc = new XmlDocument; doc.Load(response.GetResponseStream); doc.Save(Console.Out);

// Releases the resources of the response. response.Close; }   } back to the top

<div class="references_section">