C# 操作XML文檔 使用XmlDocument類方法
更新時間:2012年11月21日 11:06:51 作者:
對于很大的XML文檔,可以使用XmlReader類來讀取。因為XmlReader使用Steam(流)來讀取文件,所以不會對內存造成太大的消耗。下面就來看一下如何使用XmlDocument類,需要的朋友可以參考下
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表達式:
我們主要使用兩個方法來查詢XML文檔,SelectNodes(xpath expression)和SelectSingleNode(xpath expression)。
SelectNodes返回一個XmlNodeList對象,也就是所有符合xpath表達式的xml節(jié)點都將會被返回,你需要對返回的結果進行遍歷。
SelectSingleNode只返回第一個符合xpath表達式的節(jié)點,或者返回null。
以下面的XML文件為例,我們進行一些演示:
<?xml version="1.0" encoding="utf-8" ?>
<Customers>
<Customer id="01" city="Beijing" country="China" name="Lenovo">
<Contact gender="female" title="Support">Li Li</Contact>
</Customer>
<Customer id="02" city="Amsterdam" country="The Netherlands" name="Shell">
<Contact gender="male" title="Sales Person">Aaron Babbitt</Contact>
<Contact gender="female" title="Sales Manager">Daisy Cabell</Contact>
<Contact gender="male" title="Sales Person">Gabriel Eads</Contact>
</Customer>
</Customers>
1. 返回所有Contact節(jié)點:
XmlNodeList nodelist = xmlDoc.SelectNodes("/Customers/Customer/Contact");
foreach (XmlNode node in nodelist)
{
Console.WriteLine(node.OuterXml);
}
輸出結果為:
<Contact gender="female" title="Support">Li Li</Contact>
<Contact gender="male" title="Sales Person">Aaron Babbitt</Contact>
<Contact gender="female" title="Sales Manager">Daisy Cabell</Contact>
<Contact gender="male" title="Sales Person">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" title="Sales Person">Aaron Babbitt</Contact>
<Contact gender="female" title="Sales Manager">Daisy Cabell</Contact>
<Contact gender="male" title="Sales Person">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" title="Support">Li Li</Contact>
4. 返回含有contact名為 Li Li 的customer。注意和3的區(qū)別:
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" title="Support">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);
(三) 創(chuàng)建
以創(chuàng)建以下XML文檔為例:
<?xml version="1.0" encoding="UTF-8"?>
<Customers>
<Customer id="01" name="Lenovo" country="China" city="Beijing">
<Contact title="Support" 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標準的類??梢杂盟鼇韯?chuàng)建和查詢XML文檔。由于XmlDocument要將XML文檔的內容全部裝載進內存中,所以對于讀取內容過大的XML文檔,不適合使用XmlDocument類,而可以使用XmlReader來完成讀取。
(一) 加載
加載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 | 選取此節(jié)點的所有子節(jié)點。 |
/ | 從根節(jié)點選取。 |
// | 從匹配選擇的當前節(jié)點選擇文檔中的節(jié)點,而不考慮它們的位置。 |
. | 選取當前節(jié)點。 |
.. | 選取當前節(jié)點的父節(jié)點。 |
@ | 選取屬性。 |
我們主要使用兩個方法來查詢XML文檔,SelectNodes(xpath expression)和SelectSingleNode(xpath expression)。
SelectNodes返回一個XmlNodeList對象,也就是所有符合xpath表達式的xml節(jié)點都將會被返回,你需要對返回的結果進行遍歷。
SelectSingleNode只返回第一個符合xpath表達式的節(jié)點,或者返回null。
以下面的XML文件為例,我們進行一些演示:
復制代碼 代碼如下:
<?xml version="1.0" encoding="utf-8" ?>
<Customers>
<Customer id="01" city="Beijing" country="China" name="Lenovo">
<Contact gender="female" title="Support">Li Li</Contact>
</Customer>
<Customer id="02" city="Amsterdam" country="The Netherlands" name="Shell">
<Contact gender="male" title="Sales Person">Aaron Babbitt</Contact>
<Contact gender="female" title="Sales Manager">Daisy Cabell</Contact>
<Contact gender="male" title="Sales Person">Gabriel Eads</Contact>
</Customer>
</Customers>
1. 返回所有Contact節(jié)點:
XmlNodeList nodelist = xmlDoc.SelectNodes("/Customers/Customer/Contact");
foreach (XmlNode node in nodelist)
{
Console.WriteLine(node.OuterXml);
}
輸出結果為:
<Contact gender="female" title="Support">Li Li</Contact>
<Contact gender="male" title="Sales Person">Aaron Babbitt</Contact>
<Contact gender="female" title="Sales Manager">Daisy Cabell</Contact>
<Contact gender="male" title="Sales Person">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" title="Sales Person">Aaron Babbitt</Contact>
<Contact gender="female" title="Sales Manager">Daisy Cabell</Contact>
<Contact gender="male" title="Sales Person">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" title="Support">Li Li</Contact>
4. 返回含有contact名為 Li Li 的customer。注意和3的區(qū)別:
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" title="Support">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);
(三) 創(chuàng)建
以創(chuàng)建以下XML文檔為例:
復制代碼 代碼如下:
<?xml version="1.0" encoding="UTF-8"?>
<Customers>
<Customer id="01" name="Lenovo" country="China" city="Beijing">
<Contact title="Support" 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標準的類??梢杂盟鼇韯?chuàng)建和查詢XML文檔。由于XmlDocument要將XML文檔的內容全部裝載進內存中,所以對于讀取內容過大的XML文檔,不適合使用XmlDocument類,而可以使用XmlReader來完成讀取。