Mentioned
In
|
 |
 |
 |
 |
Microsoft Knowledge Base Article
This article contents is Microsoft Copyrighted material.
©2005-©2007 Microsoft Corporation. All rights reserved. Terms
of Use |
Trademarks
Article ID: 330589 - Last Review: August 4, 2004 - Revision: 2.4 HOW TO: Implement Common MSXML Tasks in System.xml By Using Visual C# .NETThis article was previously published under Q330589 On This PageSUMMARYThis 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 MORE INFORMATIONREQUIREMENTS- 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:
- 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
<?xml version="1.0" encoding="utf-8" ?>
<bookstore xmlns:bk="urn:samples">
<book genre="novel" publicationdate="1997" bk:ISBN="1-861001-57-6">
<title>Pride And Prejudice</title>
<price>24.95</price>
</book>
<book genre="novel" publicationdate="1992" bk:ISBN="1-861001-45-3">
<title>The New Dawn</title>
<price>29.95</price>
</book>
<book genre="novel" publicationdate="1991" bk:ISBN="1-861001-57-8">
<title>Blue Smoke</title>
<price>19.95</price>
</book>
</bookstore>
MSXML vs. System.xml for XML ProcessingThe following are the comparisons to consider when you migrate
from MSXML 4.0 to .NET Framework classes for XML. Simple API for XML (SAX)MSXML: Supports the World Wide Web (W3) Consortium final recommendation
for XML Schema with both DOM and SAX. The SAX event-based model is the most
resource-efficient and high-performance way of using MSXML..NET Framework Classes: SAX is not implemented in the .NET Framework and uses the pull
model for parsing XML. 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.
XSL TransformationMSXML: The new parser does not support asynchronous DOM load or DTD
validation. 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..NET Framework Classes: Provides incremental streaming output from the XslTransform class. 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.
XML ValidationsMSXML: MSXML 4.0 supports XML Schema. 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. .NET Framework Classes: The fast, forward-only parser that can validate XML with DTDs,
XDRs, and XSDs is named XmlValidatingReader. The XmlValidatingReader is a
XML-compliant parser. The XmlSchemaCollection class can be used to cache frequently used XSD or XDR schemas
when using XmlValidatingReader.
XML NavigationMSXML: The primary purpose of XPath is to address parts of an XML
document. 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. .NET Framework Classes: The innovative cursor-style navigation of XPathNavigator minimizes node creation to a single virtual node while providing
random access to the document. In this navigation style, a complete node tree
is not to be built in memory.
Accessing Data Over HTTPMSXML: The XMLHTTP object is integrated with MSXML to support sending the request
body directly from and parsing the response directly to the MSXML DOM objects.
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. .NET Framework Classes: System.net provides a simple programming interface for many of the protocols
used on networks. 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.
Load, Access, Manipulate, and Save XML DocumentsThe 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 MSXMLNote: To run the following MSXML sample code, see the "Requirements"
section in this article: On Error GoTo Handle
'Create the XmlDocument.
Dim objDOMDoc As New DOMDocument30
objDOMDoc.async = False
objDOMDoc.Load ("C:\XMLMigration\books.xml")
Debug.Print ("\n XML Document Loaded")
' 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 ("\n List of Publications")
Dim pbDateList As MSXML2.IXMLDOMNodeList
Set pbDateList = root.selectNodes("/bookstore/book/@publicationdate")
Dim nameList As MSXML2.IXMLDOMNodeList
Set nameList = root.selectNodes("/bookstore/book/title")
Dim i As Integer
For i = 0 To nameList.length - 1 Step i + 1
Debug.Print ("\n\t\tName: " + nameList(i).Text + ",Published :" + 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("book[@bk:ISBN='1-861001-57-6']")
' Selects the first 'Price' element and modify its value.
Set price = book.selectSingleNode("price")
price.Text = "50.5"
Debug.Print ("\n First Book Price Updated")
' Remove the last element.
root.removeChild root.lastChild
Debug.Print ("\n Last Element Deleted")
'Create a new node.
Dim elem As MSXML2.IXMLDOMElement
Set elem = objDOMDoc.createElement("book")
elem.setAttribute "genre", "novel"
elem.setAttribute "publicationdate", "1982"
' Attribute to the root namespace (another namespace)
Dim objAttribNode As MSXML2.IXMLDOMNode
Set objAttribNode = objDOMDoc.createNode(2, "bk:ISBN", "urn:samples")
objAttribNode.nodeTypedValue = "1-851002-30-1"
elem.Attributes.setNamedItem objAttribNode
'Add the node to the document.
root.appendChild elem
Debug.Print ("\n Element appended to XML Document")
objDOMDoc.save ("C:\XMLMigration\books.xml")
Debug.Print ("\n XML Document Saved")
Exit Sub
Handle:
Debug.Print ("Error: " + Err.Description)
Using .NET Framework Classes
using System;
using System.Xml;
public class CSharpSample
{
public static void Main()
{
//Create the XmlDocument.
Console.Write ("\n .NET Framework Sample\n");
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\XMLMigration\books.xml");
//Create an XmlNamespaceManager for resolving namespaces.
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("bk","urn:samples");
XmlNode book,price;
XmlElement root = doc.DocumentElement;
// Select and display the value of all the publicationdate attributes.
Console.Write ("\n List of Publications\n");
XmlNodeList pbDateList = root.SelectNodes("/bookstore/book/@publicationdate");
XmlNodeList nameList = root.SelectNodes("/bookstore/book/title");
for(int i=0;i < nameList.Count ;i++)
Console.WriteLine("\n\t\tName: " + nameList[i].InnerText + ",Published :" + pbDateList[i].InnerText);
//Select the book node with the matching attribute value.
book = root.SelectSingleNode("descendant::book[@bk:ISBN='1-861001-57-6']", nsmgr);
// Selects the first 'Price' element and modify its value.
price = book.SelectSingleNode("price");
price.InnerText = "50.5";
Console.Write ("\n First Book Price Updated");
// Remove the first element.
root.RemoveChild(root.LastChild);
Console.Write ("\n Last Element Deleted");
// Create a new node and set its attributes.
XmlElement elem = doc.CreateElement("book");
elem.SetAttribute("genre","novel");
elem.SetAttribute("publicationdate","1982");
elem.SetAttribute("ISBN","urn:samples","1-851002-30-1");
//Add the node to the document and save the XML.
root.AppendChild(elem);
Console.Write ("\n Element appended to XML Document");
doc.Save(@"C:\XMLMigration\books.xml");
Console.Write ("\n XML Document Saved");
Console.ReadLine();
}
}
Using XPathDocument for Read-only XPath QueriesTo 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(@"C:\XMLMigration\books.xml");
XPathNavigator nav = doc.CreateNavigator();
// Creating XPathExpression to select all the novels
XPathExpression expression = nav.Compile("descendant::book[@genre='novel']");
XPathNodeIterator nodeIterator = nav.Select(expression);
while (nodeIterator.MoveNext())
{
XPathNavigator nav2 = nodeIterator.Current;
Console.Write("\n\t Book Title & Price : " + nav2.Value);
nav2.MoveToNext();
}
}
}
Parsing or Validating XML DocumentsYou 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:
- On the Visual Studio .NET Tools menu, open
the Visual Studio .NET command prompt.
- Change the directory to C:\XMLMigration\
- Type the following at command line:xsd.exe
books.xml
- Notice that the following list of files is generated in
this folder:
The following code examples demonstrate how to perform
validation on books.xml using MSXML and .NET Framework classes. Using MSXML- This code creates an XMLSchemaCache40 object, adds the
schema (books.xsd) to the object, and then refers the schema of the DOMDocument
object
- Validation is performed when the books.xml file is loaded
onto the DOMDocument object.
- Validation errors are returned using the parseError
property of the DOMDocument object.
Note: To run the following MSXML sample code, see the "Requirements"
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 "", "C:\XmlMigration\books.xsd"
' 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 ("C:\XMLMigration\books.xml")
' 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 ("No Validation Errors")
End If
Exit Sub
Handle:
Debug.Print ("Validation Errors " + Err.Description)
Using .NET Framework ClassesThe .NET Framework provides the XmlValidatingReader class for validating XML Documents. To validate a XML document
using XSD schema, follow these steps:
- Create a Validating reader object.
- Specify the type of validation required.
- Register a event handler method, to deal with validation
errors.
- Read and validate the document.
- 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 + ";";
}
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(@"C:\XMLMigration\books.xml");
// load the schema file into an XmlTextReader object
XmlTextReader xsdReader = new XmlTextReader(@"C:\XMLMigration\books.xsd");
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("", 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 + " ";
}
if (validationErrors != String.Empty)
{
// errors were added during the ValidationEventHandler
char[] delimiter = new Char[1];
delimiter[0] = Convert.ToChar(";");
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("No validation errors.");
}
}
catch (Exception ex)
{
validationErrors += ex.Message + ";";
Console.WriteLine( validationErrors);
}
}
}XSLT TransformationThe following example uses Books.xsl to perform the XSLT
Transformation on Books.xml:
<?xml version='1.0'?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="bookstore">
<table><xsl:attribute name="border">1</xsl:attribute>
<TR><Td>Book Title</Td><td>Price</td></TR>
<xsl:apply-templates select="*" />
</table>
</xsl:template>
<xsl:template match="book">
<TR>
<xsl:apply-templates select="*" />
</TR>
</xsl:template>
<xsl:template match="title">
<TD>
<xsl:value-of select="."/>
</TD>
</xsl:template>
<xsl:template match="price">
<TD>
<xsl:value-of select="."/>
</TD>
</xsl:template>
</xsl:stylesheet>
Using MSXML- Synchronously load the XSLT style sheet onto a FreeThreadedDOMDocument object
- Create an instance of an XSLTemplate object.
- Set the style sheet property of the XSLTemplate object to the FreeThreadedDocument object containing the XSLT stylesheet.
- Assign the source XML node to the input property of the XSLProcessor object.
- Invoke the transformation by calling the transform() method of the XSLProcessor object.
- Obtain the results of transformation from the output
property of the XSLProcessor object.
Note: To run the following MSXML sample code, see the "Requirements"
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 ("C:\XMLMigration\books.xsl")
' 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 ("C:\XMLMigration\books.xml")
' Add a global paramter.
oXSLTProc.addParameter "TableOnly", "Yes", ""
' 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 ("Error : " & Err.Description)
Using .NET Framework ClassesTo use XSLTransform in the .NET Framework, follow these steps:
- Create an instance of an XSLTransform object.
- Using the Load() method, load an XSLT style sheet in the XSLTransform object.
- 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(@"C:\XMLMigration\books.xml");
//Create the XslTransform object.
XslTransform xslt = new XslTransform();
//Load the stylesheet.
xslt.Load(@"c:\temp\books.xsl");
FileStream stream = File.Open(@"C:\XMLMigration\books.html", FileMode.OpenOrCreate);
xslt.Transform(doc, null, stream);
}
}
Execute HTTP RequestThe following code example demonstrates how to make a request to a
Web server, and receive response from that Web server: Using MSXML Component- Create an instance of an XMLHttp object.
- Call the open() method, set HTTP parameters optionally, such as method type, URL
,custom headers or other credentials.
- Invoke the send() method to make an HTTP request.
- Check the response from the server by the following
properties:
- responseBody: returns response in an array of unsigned
bytes
- responseStream: returns response in a
stream.
- responseText: returns response as a string.
- responseXML: returns response as DOMDocument of the
XML.
Note: To run the following MSXML sample code, see the "Requirements"
section in this article:
Dim oXMLHttpRequest As New MSXML2.XMLHTTP
' Change the Microsoft Internet Information Server (IIS) name in following URL.
oXMLHttpRequest.open "GET", "http://[servername]/[virtualdirectory]/[filename.xml]", False, "", ""
oXMLHttpRequest.send
Debug.Print (oXMLHttpRequest.responseText)
Using Microsoft .NET Framework Classes- Create an instance of an HttpWebRequest object by calling the static Create() method of the WebRequest class.
- Optionally, set HTTP request attributes, such as method
type, custom headers or other credentials.
- Call the GetResponse() method of the HttpWebRequest object. This returns an HttpWebResponse object.
- Invoke the GetResponseStream method of the HttpWebResponse object to capture the body of the response.
- 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("http://[ServerName]/[virtualdir]/[filename.xml]");
// Change Username and password.
request.Credentials = new NetworkCredential("[username]", "[password]");
// 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();
}
}REFERENCES For additional
information about the System.XML namespace , click the following article
numbers to view the articles in the Microsoft Knowledge Base: 313824Â
(http://kbalertz.com/Feedback.aspx?kbNumber=313824/EN-US/
)
INFO: Roadmap for Programming XML with the DOM-Model Parser in the .NET
Framework.
313826Â
(http://kbalertz.com/Feedback.aspx?kbNumber=313826/EN-US/
)
INFO: Roadmap for XML Schemas in the .NET Framework
313651Â
(http://kbalertz.com/Feedback.aspx?kbNumber=313651/EN-US/
)
INFO:
Roadmap for XML in the .NET Framework.
318499Â
(http://kbalertz.com/Feedback.aspx?kbNumber=318499/EN-US/
)
HOW TO: Use
the System.Xml.XmlDocument Class to Execute XPath Queries in Visual C#
.NET
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
| kbdownload kbxml kbvalidation kbhowtomaster KB330589 |
Community Feedback System
Very often, it takes hours to solve a problem. Very often, you've looked high
and low, and have tried a lot of solutions. When you finally found it, chances
are, it was because someone else helped you. Here's your chance to give back.
Use our community feedback tool to let others know what worked for you and what
didn't.
Please also understand that the community feedback system is not warranted to be
correct, it's simply a system that we've built to let people try and help each
other. If something in a feedback response doesn't make sense to you, or you're
not comfortable making changes that the feedback talks about (like registry
edits), please consult a professional.
Thank you for using kbAlertz.com Feedback System.
-- Scott Cate
Be the first to leave feedback, to help others about this knowledge base
article.
(Optional) Name
(Optional)
Public URL Or Email
Comments
No
HTML -- Text Only Please
|
 |
 |
 |
 |
 |
 |
 |
| |