Using an XmlDocument Object to Store an XML Document

Using an XmlDocument Object to Store an XML Document

You use an object of the XmlDocument class to represent an XML document in a C# program. An XmlDocument object stores the nodes of the XML document in objects of the XmlNode class. You can, for example, load rows from the database into a DataSet object, and then load an XML representation of those rows into an XmlDocument object. Table 16.5 shows some of the XmlDocument properties; Table 16.6 shows some of the XmlDocument methods; and Table 16.7 shows the XmlDocument events.

Table 16.5: XmlDocument Properties

Property

Type

Description

Attributes

XmlAttributeCollection

Gets the XmlAttributeCollection object that contains the attributes of the current node.

BaseURI

string

Gets the base URI of the current node.

ChildNodes

XmlNodeList

Gets all the child nodes of the node.

DocumentElement

XmlElement

Gets the root XmlElement object for the XML document.

DocumentType

XmlDocumentType

Gets the node containing the DOCTYPE declaration.

FirstChild

XmlNode

Gets the first child of the node.

HasChildNodes

bool

Gets a bool that indicates whether this node has any child nodes.

Implementation

XmlImplementation

Gets the XmlImplementation object for the XML document.

InnerText

string

Gets or sets the concatenated values of the node and all of its children.

InnerXml

string

Gets or sets the XML that represents the children of the current node.

IsReadOnly

bool

Gets a bool value that indicates whether the current node is read-only.

LastChild

XmlNode

Gets the last child of the node.

LocalName

string

Gets the local name of the node.

Name

string

Gets the qualified name of the node.

NamespaceURI

string

Gets the namespace URI of the node.

NameTable

XmlNameTable

Gets the XmlNameTable object associated with the XML implementation.

NextSibling

XmlNode

Gets the node immediately following the current node.

NodeType

XmlNodeType

Gets the type of the current node.

OuterXml

string

Gets the XML that represents the current node and all of its children.

OwnerDocument

XmlDocument

Gets the XmlDocument object that the current node belongs to.

ParentNode

XmlNode

Gets the parent of the current node.

Prefix

string

Gets or sets the namespace prefix of the current node.

PreserveWhitespace

bool

Gets or sets a bool value that indicates whether white space is to be preserved when XML is loaded or saved. The default is false.

PreviousSibling

XmlNode

Gets the node immediately preceding the current node.

Value

string

Gets or sets the value of the current node.

XmlResolver

XmlResolver

Sets the XmlResolver object to use for resolving external resources.

Table 16.6: XmlDocument Methods

Method

Return Type

Description

AppendChild()

XmlNode

Adds the specified node to the end of child nodes.

CloneNode()

XmlNode

Creates a duplicate of the node.

CreateAttribute()

XmlAttribute

Creates an XmlAttribute object of the specified name.

CreateCDataSection()

XmlCDataSection

Creates an XmlCDataSection object with the specified data.

CreateComment()

XmlComment

Creates an XmlComment object with the specified data.

CreateDocumentFragment()

XmlDocumentFragment

Creates an XmlDocumentFragment object with the specified data.

CreateDocumentType()

XmlDocumentType

Creates a new XmlDocumentType object with the specified data.

CreateElement()

XmlElement

Overloaded. Creates an XmlElement object.

CreateEntityReference()

XmlEntityReference

Creates an XmlEntityReference object with the specified name.

CreateNavigator()

XpathNavigator

Creates an XpathNavigator object that you can use to navigate the XML document.

CreateNode()

XmlNode

Overloaded. Creates an XmlNode object.

CreateTextNode()

XmlText

Creates an XmlText object with the specified text.

CreateWhitespace()

XmlWhitespace

Creates an XmlWhitespace object.

CreateXmlDeclaration()

XmlDeclaration

Creates an XmlDeclaration object.

GetElementById()

XmlElement

Gets the XmlElement object with the specified ID.

GetElementsByTagName()

XmlNodeList

Overloaded. Returns an XmlNodeList object that contains a list of all descendant elements that match the specified name.

GetNamespaceOfPrefix()

string

Looks up the closest xmlns declaration with the specified prefix that is in scope for the current node, and then returns the namespace URI.

GetPrefixOfNamespace()

string

Looks up the closest xmlns declaration with the specified namespace URI that is in scope for the current node, and then returns the prefix.

ImportNode()

XmlNode

Imports a node from another XML document into the current XML document.

InsertAfter()

XmlNode

Inserts the specified node immediately after the specified reference node.

InsertBefore()

XmlNode

Inserts the specified node immediately before the specified reference node.

Load()

void

Overloaded. Loads XML data into your XmlDocument object.

LoadXml()

void

Loads the XML document from the specified string into your XmlDocument object.

PrependChild()

XmlNode

Adds the specified node to the beginning of the child nodes.

ReadNode()

XmlNode

Creates an XmlNode object based on the information in a specified XmlReader object. Your XmlReader must be positioned on a node or attribute.

RemoveAll()

void

Removes all the children and attributes of the current node.

RemoveChild()

XmlNode

Removes the specified child node.

ReplaceChild()

XmlNode

Replaces one child node with another.

Save()

void

Overloaded. Saves the XML document to the specified location.

SelectNodes()

XmlNodeList

Overloaded. Selects a list of nodes matching the specified XPath expression.

SelectSingleNode()

XmlNode

Overloaded. Selects the first XmlNode that matches the specified XPath expression.

WriteContentTo()

void

Saves all the children of the XML document to the specified XmlWriter object.

WriteTo()

void

Saves the XML document to the specified XmlWriter object.

Table 16.7: XmlDocument Events

Event

Event Handler

Description

NodeChanging

XmlNodeChangedEventHandler

Fires before a value in a node is changed.

NodeChanged

XmlNodeChangedEventHandler

Fires after a value in a node is changed.

NodeInserting

XmlNodeChangedEventHandler

Fires before a node is inserted.

NodeInserted

XmlNodeChangedEventHandler

Fires after a node is inserted.

NodeRemoving

XmlNodeChangedEventHandler

Fires before a node is removed.

NodeRemoved

XmlNodeChangedEventHandler

Fires after a node is removed.

Listing 16.17 shows a program that illustrates the use of an XmlDocument object. This program performs the following steps:

  1. Creates a DataSet object named myDataSet and fills it with the top two rows from the Customers table.

  2. Creates an XmlDocument object named myXmlDocument, and then loads it with the XML from myDataSet. You can use the GetXml() method to return the customer rows in myDataSet as a string containing a complete XML document. You can then use the output string from GetXml() as the input to the LoadXml() method of myXmlDocument; this loads myXmlDocument with the XML document containing the customer details.

  3. Displays the XML in myXmlDocument using the Save() method, passing Console.Out to the Save() method. This results in the XML document being displayed on the screen.

  4. Retrieves the XmlNode objects in myXmlDocument using the SelectNodes() method, and then displays the text contained in the child nodes of each XmlNode using the InnerText property. You pass an XPath expression to SelectNodes() to retrieve the required nodes.

  5. Retrieves the XmlNode for the ANATR customer using the SelectSingleNode() method, and displays the text contained in the child nodes of this XmlNode. You pass an XPath expression to SelectSingleNode() to retrieve the required node.

Listing 16.17: USINGXMLDOCUMENT.CS

start example
 /*   UsingXmlDocument.cs illustrates the use of an XmlDocument object */ using System; using System.Data; using System.Data.SqlClient; using System.Xml; class UsingXmlDocument {   public static void Main()   {     SqlConnection mySqlConnection =       new SqlConnection(         "server=localhost;database=Northwind;uid=sa;pwd=sa"       );     SqlCommand mySqlCommand = mySqlConnection.CreateCommand();     mySqlCommand.CommandText =       "SELECT TOP 2 CustomerID, CompanyName, Country "+       "FROM Customers "+       "ORDER BY CustomerID";     SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();     mySqlDataAdapter.SelectCommand = mySqlCommand;    // step 1: create a DataSet object and fill it with the top 2 rows    // from the Customers table    DataSet myDataSet = new DataSet();    mySqlConnection.Open();    mySqlDataAdapter.Fill(myDataSet, "Customers");    mySqlConnection.Close();    // step 2: create an XmlDocument object and load it with the XML from    // the DataSet; the GetXml() method returns the rows in    // myDataSet as a string containing a complete XML document; and    // the LoadXml() method loads myXmlDocument with the XML document    // string returned by GetXml()    XmlDocument myXmlDocument = new XmlDocument();    myXmlDocument.LoadXml(myDataSet.GetXml());    // step 3: display the XML in myXmlDocument using the Save() method    Console.WriteLine("Contents of myXmlDocument:");    myXmlDocument.Save(Console.Out);    // step 4: retrieve the XmlNode objects in myXmlDocument using the    // SelectNodes() method; you pass an XPath expression to SelectNodes()    Console.WriteLine("\n\nCustomers:");    foreach (XmlNode myXmlNode in      myXmlDocument.SelectNodes("/NewDataSet/Customers"))    {      Console.WriteLine("CustomerID = "+        myXmlNode.ChildNodes[0].InnerText);      Console.WriteLine("CompanyName = "+        myXmlNode.ChildNodes[1].InnerText);      Console.WriteLine("Country = "+        myXmlNode.ChildNodes[2].InnerText);    }    // step 5: retrieve the XmlNode for the ANATR customer using    // the SelectSingleNode() method; you pass an XPath    // expression to SelectSingleNode    Console.WriteLine("\nRetrieving node with CustomerID of ANATR");    XmlNode myXmlNode2 =      myXmlDocument.SelectSingleNode(        "/NewDataSet/Customers[CustomerID=\" ANATR\"]"      );    Console.WriteLine("CustomerID = "+      myXmlNode2.ChildNodes[0].InnerText);    Console.WriteLine("CompanyName = "+      myXmlNode2.ChildNodes[1].InnerText);    Console.WriteLine("Country = "+      myXmlNode2.ChildNodes[2].InnerText);   } } 
end example

Remember, you'll need to change the connection string for your SqlConnection object to connect to your database near the start of this program.

The output from this program is as follows:

 Contents of myXmlDocument: <?xml version="1.0" encoding="IBM437"?> <NewDataSet>   <Customers>     <CustomerID>ALFKI</CustomerID>     <CompanyName>Alfreds Futterkiste</CompanyName>     <Country>Germany</Country>   </Customers>   <Customers>     <CustomerID>ANATR</CustomerID>     <CompanyName>Ana Trujillo Emparedados y helados</CompanyName>     <Country>Mexico</Country>   </Customers> </NewDataSet> Customers: CustomerID = ALFKI CompanyName = Alfreds Futterkiste Country = Germany CustomerID = ANATR CompanyName = Ana Trujillo Emparedados y helados Country = Mexico Retrieving node with CustomerID of ANATR CustomerID = ANATR CompanyName = Ana Trujillo Emparedados y helados Country = Mexico 




Mastering C# Database Programming
Mastering the SAP Business Information Warehouse: Leveraging the Business Intelligence Capabilities of SAP NetWeaver
ISBN: 0764596373
EAN: 2147483647
Year: 2003
Pages: 181

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net