Use XML in. NET, read XML files, and insert data into XML documents.

Source: Internet
Author: User
This article introduces three basic XML application instances to help you quickly enter the XML programming world. Examples include: using XML in. NET, reading XML files, and inserting data into XML documents.
Use XML in. NET
If MSXML3 is used, using XML in. NET applications is quite simple. It doesn't matter if you have never touched MSXML3 in real time. You will find it easy to use the classes provided by the. NET platform.
There are two main APIs that can be used to access data created in XML documents, including forward-only unbuffered access and random access, and the Document Object Model DOM is used from beginning to end. The classes for these two APIs are located in the System. XML collection.
To quickly and effectively access data in XML documents, you need to use the XmlTextReader class. This class adopts the PULL mode, which is much better than the push mode in simple xml api (SAX. Before using the XmlTextReader class, you must first reference the System. Xml set. in C #, the "using" keyword is used for reference. in Visual Basic, the "imports" keyword is used. After the collection is referenced, you can start the reading operation as shown in the following code:
XmlTextReader reader = new XmlTextReader (pathToXmlDoc );
Int elementCount = 0;
While (reader. Read ()){
If (reader. NodeType = XmlNodeType. Element ){
ElementCount ++;
}
}
The XmlTextReader class has several different constructors. the one shown above is responsible for receiving the path of an XML file as a string parameter.
Although only the forward PULL mode is efficient, it is read-only, so you cannot insert, delete, or update XML document nodes. When you need more control over XML documents and require more flexibility, you can take a look at the Document Object Model DOM. The dom api function loads every node in the XML document into a tree structure, which looks like a "genealogy ". With this structure in the memory, it is feasible to randomly access different nodes in the XML document.
Before creating a DOM tree structure, first reference the System. Xml set and then demonstrate the XmlDocument class:
XmlDocument xmlDoc = new XmlDocument ();
XmlDoc. Load (pathToXmlDoc );
XmlNode root = xmlDoc. DocumentElement;
By using the relevant methods in the XmlDocument class, you can easily add nodes to the tree structure. The following example demonstrates how to load XML from a file and add a child element and its related attributes under the root node root:
XmlDocument xmlDoc = new XmlDocument ();
XmlDoc. Load (pathToXmlDoc );
XmlElement root = xmlDoc. DocumentElement;
XmlElement newNode = doc. CreateElement ("newNode ");
NewNode. SetAttribute ("id", "1 ");
Root. AppendChild (newNode );
After the preceding code is executed, the following XML document is generated:
<? Xml version = "1.0"?>
<Root>
<NewNode id = "1"/>
</Root>
When you need to load a string containing XML into the DOM, you can use the LoadXml () method of the XmlDocument class. After loading the file, you can operate the XML as follows:
String myXml = "<root> <someNode> Hello </someNode> </root> ";
XmlDocument xmlDoc = new XmlDocument ();
XmlDoc. LoadXml (myXml );
//... Manipulation or reading of the nodes can occur here
In addition to the above types, there are multiple classes in the System. Xml collection that can be used to execute different tasks. The above is just a simple introduction. More exercises are required for a large number of applications.
Read XML files
The following describes how to use the XmlTextReader class to read XML documents and display and output data.
System. the XML namespace defines two classes: XmlReader and XmlTextReader. The XmlTextReader class comes from the XmlReader class, And the XmlTextReader class can be used to Read XML documents. The Read function of this document reads the content of the document, until the end of the node.
The procedure is as follows:
1. Reference namespace
Because the relevant XML classes are defined in the System. XML namespace, the first thing is to reference this namespace:
Using System. Xml;
2. Open the XML document
The XmlTextReader class constructor can be used to open an XML file. The XML file of this routine is called xmltest. xml, which is located in the C: \ temp directory. The command to open the file c: \ temp \ xmltest. xml is as follows:
XmlTextReader reader = new XmlTextReader ("C: \ temp \ xmltest. xml ");
3. Read data
To Read data from an XML file, you can use the Read method of the XmlTextReader class:
While (reader. Read ())
{
Console. WriteLine (reader. Name );
}
4. Complete Execution Code readxml. cs
Namespace WriteToXML
{
Using System;
Using System. Xml;
/// <Summary>
/// Summary description for Class1.
/// </Summary>
Public class Class1
{
Public Class1 ()
{
}
Public static int Main (string [] args)
{
Try
{
XmlTextWriter writer = new XmlTextWriter ("C: \ temp \ xmltest. xml", null );
Writer. WriteStartDocument ();
Writer. WriteComment ("Commentss: XmlWriter Test Program ");
Writer. WriteProcessingInstruction ("Instruction", "Person Record ");
Writer. WriteStartElement ("p", "person", "urn: person ");
Writer. WriteStartElement ("LastName ","");
Writer. WriteString ("Chand ");
Writer. WriteEndElement ();
Writer. WriteStartElement ("FirstName ","");
Writer. WriteString ("Chand ");
Writer. WriteEndElement ();
Writer. WriteElementInt16 ("age", "", 25 );
Writer. WriteEndDocument ();
}
Catch (Exception e)
{
Console. WriteLine ("Exception: {0}", e. ToString ());
}
Return 0;
}
}
}
Insert data to the XML document
To insert XML data into an existing or new document, you can use the XmlNode class and XmlDocument class. The specific implementation steps are as follows:
1. Reference namespace
Because the relevant XML classes are defined in the System. XML namespace, the first thing is to reference this namespace:
Using System. Xml;
2. load XML into the document
We can use the LoadXml method of XmlDocument to load XML data into a document or an existing XML document. The following code loads XML data to the document:
XmlDocument doc = new XmlDocument ();
Doc. LoadXml ("<XMLFile>" +
"<SomeData> Old Data </SomeData>" +
"</XMLFile> ");
3. Insert XML data
The following code inserts XML data into a file and saves it as InsertedDoc. xml:
Try
{
XmlNode currNode;
XmlDocument doc = new XmlDocument ();
Doc. LoadXml ("<XMLFile>" +
"<SomeData> Old Data </SomeData>" +
"</XMLFile> ");
XmlDocumentFragment docFrag = doc. CreateDocumentFragment ();
DocFrag. InnerXml = "<Inserted>" +
"<NewData> Inserted Data </NewData>" +
"</Inserted> ";
// Insert the availability node into the document
CurrNode = doc. DocumentElement. FirstChild;
CurrNode. InsertAfter (docFrag, currNode. LastChild );
// Save the output to a file
Doc. Save ("InsertedDoc. xml ");
}
Catch (Exception e)
{
Console. WriteLine ("Exception: {0}", e. ToString ());
}
After the code is executed, the content of the new document is as follows:
-<XMLFile>
-<SomeData>
Old Data
-<Inserted>
<NewData> Inserted Data </NewData>
</Inserted>
</SomeData>
</XMLFile>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.