Details of net documentation

  • 2020-12-21 18:01:04
  • OfStack

1. XML-related namespaces in the Net framework

System.Xml
Contains 1 class related to read and write operations on XML documents: XmlReader, XmlTextReader, XmlValidatingReader, XmlNodeReader, XmlWriter, XmlTextWriter and XmlNode (subclasses of which include XmlDocument, XmlDataDocument, XmlDocumentFragment).

System.Xml.Schema
Contains the classes associated with the XML schema, including the classes XmlSchema, XmlSchemaAll, XmlSchemaXPath, and XmlSchemaType.

System.Xml.Serialization
Contains classes related to the serialization and deserialization of XML documents.
Serialization: Converts data in XML format to data in stream format and can be transmitted over the network;
Deserialization: To do the opposite, restore data in stream format to data in XML format.

System.Xml.Xpath
Contains XPathDocument, XPathExression, XPathNavigator, and XPathNodeIterator classes that perform the navigation functions of XML documents.
(With the help of the XPathDocument class, the XPathNavigator class performs fast XML document navigation, which provides the programmer with many Move methods for navigation.)

System.Xml.Xsl
Complete the conversion function of XSLT.

2. How to write XML documents

Write with the XmlWriter class, which contains the methods and properties needed to write XML documents, is the base class for the XmlTextWriter and XmlNodeWriter classes.

Some methods for write operations come in pairs. For example, to write an element, you first call the WriteStartElement method -- > Write the actual content -- > Calling the WriteEndElement method ends.

The following subclass, XmlTextWriter, shows how to write XML documents.

XmlTextWriter textWriter = New XmlTextWriter("C:\\myXmFile.xml", null);

After the object is created, we call the WriterStartDocument method to start writing the XML document.
When the write is complete, call WriteEndDocument to finish the write and call the Close method to close it.

In writing, we can:
Call the WriteComment method to add the description;
Add a string by calling the WriteString method;
Add an element by calling WriteStartElement and WriteEndElement method pairs;
Add 1 attribute by calling WriteStartAttribute and WriteEndAttribute method pairs;
Add the entire 1 node by calling the WriteNode method;
Other methods of writing include WriteProcessingInstruction, WriteDocType, and so on.

The following examples show how to use these methods to write an XML document.


using System;
using System.Xml;  
namespace WriteXML
{
 class Class1
 {
  static void Main( string[] args )
  {
   try
   {
    //  create XmlTextWriter An instance object of a class 
    XmlTextWriter textWriter = new XmlTextWriter("C:\\w3sky.xml", null);
    textWriter.Formatting = Formatting.Indented;
    //  Start the write procedure, call WriteStartDocument methods 
    textWriter.WriteStartDocument();  
    //  Written instructions 
    textWriter.WriteComment("First Comment XmlTextWriter Sample Example");
    textWriter.WriteComment("w3sky.xml in root dir");   
    // create 1 A node 
    textWriter.WriteStartElement("Administrator");
    textWriter.WriteElementString("Name", "formble");
    textWriter.WriteElementString("site", "w3sky.com");
    textWriter.WriteEndElement();

    //  End of writing document, call WriteEndDocument methods 
    textWriter.WriteEndDocument();
    //  Shut down textWriter
    textWriter.Close();
   }
   catch(System.Exception e)
   {
    Console.WriteLine(e.ToString());
   }
  }
 }
}

3. Methods for reading XML documents

The XML document is read with an object of the XmlTextReader class. Simply indicate the location of the XML file in the constructor that creates the new object.

XmlTextReader textReader = new XmlTextReader("C:\\books.xml");

The attribute NodeType in the XmlTextReader class knows the node type of its node. By comparing the elements in the enumerated type XmlNodeType, you can get the node type of the corresponding node and do something about it.

Enumerated types XmlNodeType contain types of XML items such as XmlDeclaration, Attribute, CDATA, Element, Comment, Document, DocumentType, Entity, ProcessInstruction, and WhiteSpace.

The following example creates an object by reading the "ES139en.xml" file, and gets the information from the xml object's Name, BaseURI, Depth, LineNumber, and so on, and displays it in the console. (Use the "books.xml" file attached to the ES146en.net development tool as an example.)


using System;
using System.Xml;  
namespace ReadXml
{
    class Class1
    {
        static void Main( string[] args )
        {
            //  create 1 a XmlTextReader Class object and call Read Method to read XML file 
            XmlTextReader textReader  = new XmlTextReader("C:\\books.xml");
            textReader.Read();
            //  If the node is not empty, the body of the loop is executed 
            while ( textReader.Read() )
            {
                //  Read the first 1 An element 
                textReader.MoveToElement();
                Console.WriteLine("XmlTextReader Properties Test");
                Console.WriteLine("===================");  
                //  The attributes of the element are read and displayed in the console 
                Console.WriteLine("Name:" + textReader.Name);
                Console.WriteLine("Base URI:" + textReader.BaseURI);
                Console.WriteLine("Local Name:" + textReader.LocalName);
                Console.WriteLine("Attribute Count:" + textReader.AttributeCount.ToString());
                Console.WriteLine("Depth:" + textReader.Depth.ToString());
                Console.WriteLine("Line Number:" + textReader.LineNumber.ToString());
                Console.WriteLine("Node Type:" + textReader.NodeType.ToString());
                Console.WriteLine("Attribute Count:" + textReader.Value.ToString());
            }
        }
    }
}

4. Use XmlDocument class

The XmlDocument class, which represents the XML document, can perform various operations related to the entire XML document, while the XmlDataDocument class associated with it is also very important and worthy of further study. This class contains important methods such as Load, LoadXml, and Save.

Load method: You can import XML data from 1 XML file specified by a string, or 1 stream object, 1 TextReader object, and 1 XmlReader object.
The LoadXml method completes the function of importing XML data from a specific XML file.
The Save method: saves the XML data to 1 XML file or to 1 stream object, 1 TextWriter object, and 1 XmlWriter object.

In the following example, the LoadXml method of the XmlDocument class object is used to read XML data from an XML document segment and call its Save method to save the data in a file.


//  create 1 a XmlDocument The object of the class 
XmlDocument doc = new XmlDocument();
doc.LoadXml(("<Student type='regular' Section='B'><Name>Tommy Lex</Name></Student>"));
//  Save to a file 
doc.Save("C:\\student.xml");

//  You can also change it Save Method, will XML The data is displayed in the console as follows:  
doc.Save(Console.Out);
 In the following example, it is used 1 a XmlTextReader Object, through which to read "books.xml" In the file XML The data. Then create a 1 a XmlDocument Object and load XmlTextReader Object, like this XML The data is read XmlDocument Object is in. Finally, through the object's Save Method will be XML The data is displayed in the console. 

XmlDocument doc = new XmlDocument();
//  create 1 a XmlTextReader Object, read XML data 
XmlTextReader reader = new XmlTextReader("c:\\books.xml");
reader.Read();
//  load XmlTextReader The object of the class 
doc.Load(reader);
//  will XML The data is displayed in the console 
doc.Save(Console.Out);

xml file


<?xml version='1.0'?>
<!-- This file represents a fragment of a book store inventory database -->
<bookstore>
  <book genre="autobiography" publicationdate="1981" ISBN="1-861003-11-0">
    <title>The Autobiography of Benjamin Franklin</title>
    <author>
      <first-name>Benjamin</first-name>
      <last-name>Franklin</last-name>
    </author>
    <price>8.99</price>
  </book>
  <book genre="novel" publicationdate="1967" ISBN="0-201-63361-2">
    <title>The Confidence Man</title>
    <author>
      <first-name>Herman</first-name>
      <last-name>Melville</last-name>
    </author>
    <price>11.99</price>
  </book>
  <book genre="philosophy" publicationdate="1991" ISBN="1-861001-57-6">
    <title>The Gorgias</title>
    <author>
      <first-name>Sidas</first-name>
      <last-name>Plato</last-name>
    </author>
    <price>9.99</price>
  </book>
</bookstore>

Another example of.net operating the xml file


// Sets the physical path to the configuration file 
    public string xmlPath = "/manage/spider/config.xml";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // Set the physical path of the program + File physical path 
            string path = Request.PhysicalApplicationPath + xmlPath;
            // To obtain XML The element object 
            XElement config = XElement.Load(path);
            if (config != null)
            {
                // Get the node point element 
                XElement eleAmazonDetailUrl = config.Element("AmazonDetailUrl");
                XElement eleAmazonListUrl = config.Element("AmazonListUrl");
                XElement eleHz = config.Element("Hz");
                XElement eleCount = config.Element("Count");
                // Renders the retrieved data on the page 
                if (eleAmazonDetailUrl != null)
                    TextBox_AmazonDetailUrl.Text = eleAmazonDetailUrl.Value;
                if (eleAmazonListUrl != null)
                    TextBox_AmazonListUrl.Text = eleAmazonListUrl.Value;
                if (eleHz != null)
                    TextBox_Hz.Text = eleHz.Value;
                if (eleCount != null)
                    TextBox_Count.Text = eleCount.Value;
            }
            else
                Response.Write("");
        }
    }
    protected void btn_Save_Click(object sender, EventArgs e)
    {
        // Set up the XML The file path 
        string path = Request.PhysicalApplicationPath + xmlPath;
        // Sets the name and content of the node 
        XElement root = new XElement("Settings",
             new XElement("AmazonDetailUrl", TextBox_AmazonDetailUrl.Text.Trim()),
             new XElement("AmazonListUrl", TextBox_AmazonListUrl.Text.Trim()),
             new XElement("Hz", TextBox_Hz.Text.Trim()),
             new XElement("Count", TextBox_Count.Text.Trim())
                 );
        // Serializes the element to the specified path XML The file of 
        root.Save(path);
     }


Related articles: