通過XmlDocument讀寫Xml文檔

來源:互聯網
上載者:User
通過XmlDocument讀寫Xml文檔 什麼是Xml?
Xml是擴充標記語言的簡寫,是一種開發的文字格式設定。關於它的更多情況可以通過w3組織瞭解http://www.w3.org/TR/1998/REC-xml-19980210。如果你不知道它,那你就out太多了。 .Net是如何處理Xml的?
1.通過XmlDocument讀寫Xml文檔2.使用XmlReader讀Xml,使用XmlWriter寫Xml3.使用Linq to xml存取XML4.通過XmlScheme定義固定格式xml文檔5.Xml序列化或者還原序列化類6.通過XPath尋找Xml節點7.通過Xslt轉化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到節點的屬性集合。

轉載地址:http://www.cnblogs.com/yukaizhao/archive/2011/07/19/csharp_xmldocument_access_xml.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.