程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#基礎知識 >> C# 操作XML文檔 使用XmlDocument類方法

C# 操作XML文檔 使用XmlDocument類方法

編輯:C#基礎知識
W3C制定了XML DOM標准。很多編程語言中多提供了支持W3C XML DOM標准的API。我在之前的文章中介紹過如何使用Javascript對XML文檔進行加載與查詢。在本文中,我來介紹一下.Net中的XmlDocument類。它支持並擴展了W3C XML DOM標准。它將整個XML文檔都先裝載進內存中,然後再對XML文檔進行操作,所以如果XML文檔內容過大,不建議使用XmlDocument類,因為會消耗過多內存。對於很大的XML文檔,可以使用XmlReader類來讀取。因為XmlReader使用Steam(流)來讀取文件,所以不會對內存造成太大的消耗。下面就來看一下如何使用XmlDocument類。
(一) 加載
加載XML比較常用的有三種方法:
public virtual void Load(string filename);
public virtual void Load(Stream inStream);
public virtual void LoadXml(string xml);
下面代碼演示如何使用它們:
代碼如下:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("XMLFile1.xml");
Entity retrievedAnnotation = _orgService.Retrieve("annotation"
, new Guid("C1B13C7F-F430-E211-8FA1-984BE1731399"), new ColumnSet(true));
byte[] fileContent = Convert.FromBase64String(retrievedAnnotation["documentbody"].ToString());
MemoryStream ms = new MemoryStream(fileContent);
XmlDocument xmlDoc2 = new XmlDocument();
xmlDoc2.Load(ms);
string str = @"<Customers><Customer id='01' city='Beijing' country='China' name='Lenovo'/></Customers>";
XmlDocument xmlDoc3 = new XmlDocument();
xmlDoc3.LoadXml(str);

(二) 查詢
對XML的元素、屬性、文本的查詢可以使用XPath。具體的定義可以參看w3school。
首先應該了解一下XPath表達式:
表達式 描述 nodename 選取此節點的所有子節點。 / 從根節點選取。 // 從匹配選擇的當前節點選擇文檔中的節點,而不考慮它們的位置。 . 選取當前節點。 .. 選取當前節點的父節點。 @ 選取屬性。
我們主要使用兩個方法來查詢XML文檔,SelectNodes(xpath expression)和SelectSingleNode(xpath expression)。
SelectNodes返回一個XmlNodeList對象,也就是所有符合xpath表達式的xml節點都將會被返回,你需要對返回的結果進行遍歷。
SelectSingleNode只返回第一個符合xpath表達式的節點,或者返回null。
以下面的XML文件為例,我們進行一些演示:
代碼如下:

<?xml version="1.0" encoding="utf-8" ?>
<Customers>
<Customer id="01" city="Beijing" country="China" name="Lenovo">
<Contact gender="female">Li Li</Contact>
</Customer>
<Customer id="02" city="Amsterdam" country="The Netherlands" name="Shell">
<Contact gender="male">Aaron Babbitt</Contact>
<Contact gender="female">Daisy Cabell</Contact>
<Contact gender="male">Gabriel Eads</Contact>
</Customer>
</Customers>

1. 返回所有Contact節點:
XmlNodeList nodelist = xmlDoc.SelectNodes("/Customers/Customer/Contact");
foreach (XmlNode node in nodelist)
{
Console.WriteLine(node.OuterXml);
}
輸出結果為:
<Contact gender="female">Li Li</Contact>
<Contact gender="male">Aaron Babbitt</Contact>
<Contact gender="female">Daisy Cabell</Contact>
<Contact gender="male">Gabriel Eads</Contact>
2. 返回id為02的customer:
XmlNode node = xmlDoc.SelectSingleNode("/Customers/Customer[@id='02']");
Console.WriteLine(node.OuterXml);
輸出結果為:
<Customer id="02" city="Amsterdam" country="The Netherlands" name="Shell">
<Contact gender="male">Aaron Babbitt</Contact>
<Contact gender="female">Daisy Cabell</Contact>
<Contact gender="male">Gabriel Eads</Contact>
</Customer>
3. 返回含有contact名為Li Li的contact:
XmlNode node = xmlDoc.SelectSingleNode("/Customers/Customer/Contact[text()='Li Li']");
Console.WriteLine(node.OuterXml);
輸出結果:
<Contact gender="female">Li Li</Contact>
4. 返回含有contact名為 Li Li 的customer。注意和3的區別:
XmlNode node = xmlDoc.SelectSingleNode("/Customers/Customer[Contact/text()='Li Li']");
Console.WriteLine(node.OuterXml);
輸出結果:
<Customer id="01" city="Beijing" country="China" name="Lenovo">
<Contact gender="female">Li Li</Contact>
</Customer>
5. (1) 獲取outer xml:
XmlNode node = xmlDoc.SelectSingleNode("/Customers/Customer[@id='02']");
Console.WriteLine(node.OuterXml);
(2) 獲取 inner xml:
XmlNode node = xmlDoc.SelectSingleNode("/Customers/Customer[@id='02']");
Console.WriteLine(node.InnerXml);
(3) 獲取 text
XmlNode node = xmlDoc.SelectSingleNode("/Customers/Customer/Contact[text()='Li Li']");
Console.WriteLine(node.InnerText);
(4) 獲取屬性
XmlNode node = xmlDoc.SelectSingleNode("/Customers/Customer/Contact[text()='Li Li']");
Console.WriteLine(node.Attributes["gender"].Value);
(三) 創建
以創建以下XML文檔為例:
代碼如下:

<?xml version="1.0" encoding="UTF-8"?>
<Customers>
<Customer id="01" name="Lenovo" country="China" city="Beijing">
<Contact gender="female">Li Li</Contact>
</Customer>
</Customers>

代碼如下:

var xmlDoc = new XmlDocument();
//Create the xml declaration first
xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null));
//Create the root node and append into doc
var el = xmlDoc.CreateElement("Customers");
xmlDoc.AppendChild(el);
// Customer Lenovo
XmlElement elementCustomer = xmlDoc.CreateElement("Customer");
XmlAttribute attrID = xmlDoc.CreateAttribute("id");
attrID.Value = "01";
elementCustomer.Attributes.Append(attrID);
XmlAttribute cityID = xmlDoc.CreateAttribute("city");
cityID.Value = "Beijing";
elementCustomer.Attributes.Append(cityID);
XmlAttribute attrCountry = xmlDoc.CreateAttribute("country");
attrCountry.Value = "China";
elementCustomer.Attributes.Append(attrCountry);
XmlAttribute nameCountry = xmlDoc.CreateAttribute("name");
nameCountry.Value = "Lenovo";
elementCustomer.Attributes.Append(nameCountry);
el.AppendChild(elementCustomer);
// Contact Li Li
XmlElement elementContact = xmlDoc.CreateElement("Contact");
elementContact.InnerText = "Li Li";
XmlAttribute attrGender = xmlDoc.CreateAttribute("gender");
attrGender.Value = "female";
elementContact.Attributes.Append(attrGender);
XmlAttribute titleGender = xmlDoc.CreateAttribute("title");
titleGender.Value = "Support";
elementContact.Attributes.Append(titleGender);
elementCustomer.AppendChild(elementContact);
xmlDoc.Save("test.xml");

總結: XmlDocument類是.Net API中提供的支持W3C XML DOM標准的類。可以用它來創建和查詢XML文檔。由於XmlDocument要將XML文檔的內容全部裝載進內存中,所以對於讀取內容過大的XML文檔,不適合使用XmlDocument類,而可以使用XmlReader來完成讀取。
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved