通過XmlDocument讀寫Xml文檔


通過XmlDocument讀寫Xml文檔
有如下一段Xml:
<?xml version="1.0" encoding="utf-8" ?>
<students>
  <!--我是一段註釋文字-->
  <student name="張平">
    <courses>
      <course name="語文?">
        <teacherComment>
          <![CDATA[
        這裏是語文老師的批註
        ]]>
        </teacherComment>     
    </course>
 
      <course name="數學">
        <teacherComment>
          <![CDATA[
        這裏是數學老師的批註
        ]]>
        </teacherComment>
      </course>
    </courses>
  </student>
</students>
1.如何使用XmlDocument讀取Xml

我要用一段代碼遍歷所有Student,並打印Student的所有屬性和子節點的值
/*玉開博客 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);
 
            //使用xpath表達式選擇文檔中所有的student子節點
            XmlNodeList studentNodeList = doc.SelectNodes("/students/student");
            if (studentNodeList != null)
            {
                foreach (XmlNode studentNode in studentNodeList)
                {
                    //通過Attributes獲得屬性名字爲name的屬性
                    string name = studentNode.Attributes["name"].Value;
                    Console.WriteLine("Student:" + name);
 
                    //通過SelectSingleNode方法獲得當前節點下的courses子節點
                    XmlNode coursesNode = studentNode.SelectSingleNode("courses");
 
                    //通過ChildNodes屬性獲得courseNode的所有一級子節點
                    XmlNodeList courseNodeList = coursesNode.ChildNodes;
                    if (courseNodeList != null)
                    {
                        foreach (XmlNode courseNode in courseNodeList)
                        {
                            Console.Write("\t");
                            Console.Write(courseNode.Attributes["name"].Value);
                            Console.Write("老師評語");
                            //通過FirstNode屬性可以獲得課程節點的第一個子節點,LastNode可以獲得最後一個子節點
                            XmlNode teacherCommentNode = courseNode.FirstChild;
                            //讀取CData節點
                            XmlCDataSection cdata = (XmlCDataSection)teacherCommentNode.FirstChild;
                            Console.WriteLine(cdata.InnerText.Trim());
                        }
                    }
                }
            }
 
            Console.Write("\r\nPress any key to continue....");
            Console.Read();
        }
    }
}
XmlDocument本身是從XmlNode繼承的,讀Xml節點可以通過FirstChild,LastChild,或者NextSibling,PreviousSibling讀取單個節點,或者通過ChildNodes讀取所有子節點。還可以使用XPath表達式使用SelectNodes(string xpath)或者SelectSingleNode(string xpath)讀取單個或者多個符合條件的節點。
2.如何通過XmlDocument編輯Xml
同樣是讀取Xml中的xml例子,我們這次要用csharp代碼生成xml,如下代碼:
/*玉開博客 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();
            //創建Xml聲明部分,即<?xml version="1.0" encoding="utf-8" ?>
            xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "yes");
 
            //創建根節點
            XmlNode rootNode = xmlDoc.CreateElement("students");
 
            //創建student子節點
            XmlNode studentNode = xmlDoc.CreateElement("student");
            //創建一個屬性
            XmlAttribute nameAttribute = xmlDoc.CreateAttribute("name");
            nameAttribute .Value = "張同學";
            //xml節點附件屬性
            studentNode.Attributes.Append(nameAttribute);
 
            
            //創建courses子節點
            XmlNode coursesNode = xmlDoc.CreateElement("courses");
            XmlNode courseNode1 = xmlDoc.CreateElement("course");
            XmlAttribute courseNameAttr = xmlDoc.CreateAttribute("name");
            courseNameAttr.Value = "語文";
            courseNode1.Attributes.Append(courseNameAttr);
            XmlNode teacherCommentNode = xmlDoc.CreateElement("teacherComment");
            //創建Cdata塊
            XmlCDataSection cdata = xmlDoc.CreateCDataSection("<font color=\"red\">這是語文老師的批註</font>");
            teacherCommentNode.AppendChild(cdata);
            courseNode1.AppendChild(teacherCommentNode);
            coursesNode.AppendChild(courseNode1);
            //附加子節點
            studentNode.AppendChild(coursesNode);
 
            rootNode.AppendChild(studentNode);
            //附加根節點
            xmlDoc.AppendChild(rootNode);
 
            //保存Xml文檔
            xmlDoc.Save(@"d:\test.xml");
 
            Console.WriteLine("已保存Xml文檔");
 
 
        }
    }
}

使用XmlDocument生成xml的要點在於使用xmlDocument的實例的CreateElement創建XmlNode或者通過CreateAttribute方法創建屬性,並通過AppendChild方法附加xml節點,通過AppendAttribute附加Attribute到節點的屬性集合。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章