Read and Write XML documents through xmldocument

Source: Internet
Author: User
Tags cdata
Read and Write XML documents through xmldocument What is XML?
XML is short for the Extended Markup Language and a developed text format. For more information, see the W3 organization for http://www.w3.org/tr/1998/rec-xml-19980210. If you don't know about it, you will be out too much. How does. Net Process XML?
1. read and Write XML documents through xmldocument 2. use xmlreader to read XML, use xmlwriter to write xml3. use LINQ to XML to access xml4. use xmlscheme to define fixed-format XML documents. 5. XML serialization or deserialization Class 6. search for XML nodes using XPath 7. convert XML format using XSLT Read and Write XML documents through xmldocumentThere is the following XML :?
<?xml
version="1.0"
encoding="utf-8"
?> <students>
  <! -- I am a text comment -->  <student
name="Zhang Ping">
    <courses>
      <course
name="Language? ">
        <teacherComment>
          <![CDATA[
        Here is the comment of the Chinese teacher
        ]]>        </teacherComment>      
    </course>
        <course
name="Mathematics">
        <teacherComment>
          <![CDATA[
        Here is the comments from the math.
        ]]>        </teacherComment>
      </course>
    </courses>
  </student>
</students>
1. How to Use xmldocument to read XML
I will use a piece of code to traverse all student and print all attributes of student and the value of the subnode?
/* Yukai blog
Http://www.cnblogs.com/yukaizhao */
using
System;
using
System.Collections.Generic;
using
System.Text;
using
System.Xml;
  namespace
XmlExample {     class
Program     {
        static
void Main(string[] args)
        {
            string
xmlFilePath = @"X:\about.net\example\XmlExample\1.xml";
            XmlDocument doc =
new XmlDocument();
            doc.Load(xmlFilePath);
              // Use the XPath expression to select all student subnodes in the document
            XmlNodeList studentNodeList = doc.SelectNodes("/students/student");
            if
(studentNodeList != null)
            {
                foreach
(XmlNode studentNode in
studentNodeList)                 {
                    // Get the attribute named name through attributes
                    string
name = studentNode.Attributes["name"].Value;
                    Console.WriteLine("Student:"
+ name);                       // Obtain the courses subnode under the current node through the selectsinglenode Method
                    XmlNode coursesNode = studentNode.SelectSingleNode("courses");
                      // Obtain all level 1 subnodes of coursenode through the childnodes attribute
                    XmlNodeList courseNodeList = coursesNode.ChildNodes;
                    if
(courseNodeList != null)
                    {
                        foreach
(XmlNode courseNode in
courseNodeList)                         {
                            Console.Write("\t");
                            Console.Write(courseNode.Attributes["name"].Value);
                            Console.Write("Instructor comment");
                            // You can obtain the first subnode of the course node through the firstnode attribute, and the lastnode can obtain the last subnode.
                            XmlNode teacherCommentNode = courseNode.FirstChild;
                            // Read the CDATA Node
                            XmlCDataSection cdata = (XmlCDataSection)teacherCommentNode.FirstChild;
                            Console.WriteLine(cdata.InnerText.Trim());
                        }
                    }
                }
            }
              Console.Write("\r\nPress any key to continue....");
            Console.Read();
        }
    }
}
Xmldocument itself is inherited from xmlnode. To read XML nodes, you can use firstchild, lastchild, nextsibling, and previussibling to read a single node, or read all child nodes through childnodes. You can also use the XPath expression selectnodes (string XPath) or selectsinglenode (string XPath) to read one or more qualified nodes. 2. How to edit XML through xmldocumentThis is also an example of reading XML in XML. We will use the CSHARP code to generate xml, as shown in the following code :?
/* Yukai blog
Http://www.cnblogs.com/yukaizhao */
using
System;
using
System.Collections.Generic;
using
System.Text;
using
System.Xml;
  namespace
WriteXml {     class
Program     {
        static
void Main(string[] args)
        {
            XmlDocument xmlDoc =
new XmlDocument();
            // Create the XML declaration section, that is, <? XML version = "1.0" encoding = "UTF-8"?>
            xmlDoc.CreateXmlDeclaration("1.0",
"utf-8",
"yes");               // Create the root node
            XmlNode rootNode = xmlDoc.CreateElement("students");
              // Create a student subnode
            XmlNode studentNode = xmlDoc.CreateElement("student");
            // Create an attribute
            XmlAttribute nameAttribute = xmlDoc.CreateAttribute("name");
            nameAttribute .Value =
"Classmate Zhang";             // XML node attachment attributes
            studentNode.Attributes.Append(nameAttribute);
                           // Create a courses subnode
            XmlNode coursesNode = xmlDoc.CreateElement("courses");
            XmlNode courseNode1 = xmlDoc.CreateElement("course");
            XmlAttribute courseNameAttr = xmlDoc.CreateAttribute("name");
            courseNameAttr.Value =
"Language";             courseNode1.Attributes.Append(courseNameAttr);
            XmlNode teacherCommentNode = xmlDoc.CreateElement("teacherComment");
            // Create a CDATA Block
            XmlCDataSection cdata = xmlDoc.CreateCDataSection("<Font color = \" Red \ "> This is a Chinese instructor's comment </font>");
            teacherCommentNode.AppendChild(cdata);
            courseNode1.AppendChild(teacherCommentNode);
            coursesNode.AppendChild(courseNode1);
            // Add a subnode
            studentNode.AppendChild(coursesNode);
              rootNode.AppendChild(studentNode);
            // Add the root node
            xmlDoc.AppendChild(rootNode);
              // Save the XML document
            xmlDoc.Save(@"d:\test.xml");
              Console.WriteLine("Saved XML document");
            }
    }
}

The main point of generating XML using xmldocument is to use createelement of the xmldocument instance to create an xmlnode or use the createattribute method to create an attribute, appendchild to attach an XML node, and appendattribute to the attribute set of the node through appendattribute.

Address: http://www.cnblogs.com/yukaizhao/archive/2011/07/19/csharp_xmldocument_access_xml.html

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.