簡單用一個範例介紹
以下幾點附註
1. 使用 namespace : System.Xml
2. XmlDocument.Load() : 是讀取一整個XML檔案
XmlDocument.LoadXml() : 是讀取一整個 string , 剛好事由XML 轉出或符合XML 格式的 字串
3. node.Attributes :紀錄自行定義的 屬性,
如在 'Root' 中 定義了 一個 attribute 叫 'local' 值是 'false'
4. System.Xml.XmlNodeType :
是 node 的 type ,在此例只會出現兩種 type Text 和 Element.
如 'Root'節點中的第一個子節點 就是 Text 的Type , 是字串 "The Root Value"
這是xml file
<?xml version = "1.0"?>
<Root Local="false">
The Root Value
<node1 color="green" type="myType">
this is node 1
</node1>
<node2 >
node 2 !
</node2>
</Root>
以下是 code
           string theAllText = "";
           string  theRootAttributeName = "" ;
           string theRootAttributeValue = "";
           /// Declare the xml Doc
           XmlDocument xmlDoc = new XmlDocument();
           xmlDoc.Load("MyTest.xml");
           /// Get the first level nodes
           XmlNodeList xmlFile = xmlDoc.ChildNodes;
           /// The XML head info
           XmlNode nodeXmlInfo = xmlFile[0];
           /// The record node
           XmlNode node = xmlFile[1];
           /// show the all XML text
           theAllText = node.InnerText;
          
           /// Show the first level attribute count
           if (node.Attributes.Count > 0)
           {
               theRootAttributeName = node.Attributes[0].Name;
               theRootAttributeValue = node.Attributes[0].Value;
           }
           /// Show the RootInfo
           Console.WriteLine("The total inner text :    " +theAllText);
           Console.WriteLine("the Root AttributeName" + theRootAttributeName);
           Console.WriteLine("the Root AttributeValue" + theRootAttributeValue);
           ///----------------------
           /// Load the second layer
           ///----------------------
           /// Get the first nodes
           ///  xmlFile[1].ChildNodes.Count 子節點的數目
           for (int i = 0; i < thesecondlyearnode =" xmlFile[1].ChildNodes[i];" nodetype ="="">
參考網址
http://support.microsoft.com/kb/301233/zh-tw
http://msdn.microsoft.com/en-us/library/system.xml.xmldatadocument.aspx
http://www.aicuxiao.com/code/view2983.html
 
沒有留言:
張貼留言