C# 操作XML文檔 使用XmlDocument類方法
更新時(shí)間:2012年11月21日 11:06:51 作者:
對(duì)于很大的XML文檔,可以使用XmlReader類來讀取。因?yàn)閄mlReader使用Steam(流)來讀取文件,所以不會(huì)對(duì)內(nèi)存造成太大的消耗。下面就來看一下如何使用XmlDocument類,需要的朋友可以參考下
W3C制定了XML DOM標(biāo)準(zhǔn)。很多編程語言中多提供了支持W3C XML DOM標(biāo)準(zhǔn)的API。我在之前的文章中介紹過如何使用Javascript對(duì)XML文檔進(jìn)行加載與查詢。在本文中,我來介紹一下.Net中的XmlDocument類。它支持并擴(kuò)展了W3C XML DOM標(biāo)準(zhǔn)。它將整個(gè)XML文檔都先裝載進(jìn)內(nèi)存中,然后再對(duì)XML文檔進(jìn)行操作,所以如果XML文檔內(nèi)容過大,不建議使用XmlDocument類,因?yàn)闀?huì)消耗過多內(nèi)存。對(duì)于很大的XML文檔,可以使用XmlReader類來讀取。因?yàn)閄mlReader使用Steam(流)來讀取文件,所以不會(huì)對(duì)內(nèi)存造成太大的消耗。下面就來看一下如何使用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);
(二) 查詢
對(duì)XML的元素、屬性、文本的查詢可以使用XPath。具體的定義可以參看w3school。
首先應(yīng)該了解一下XPath表達(dá)式:
我們主要使用兩個(gè)方法來查詢XML文檔,SelectNodes(xpath expression)和SelectSingleNode(xpath expression)。
SelectNodes返回一個(gè)XmlNodeList對(duì)象,也就是所有符合xpath表達(dá)式的xml節(jié)點(diǎn)都將會(huì)被返回,你需要對(duì)返回的結(jié)果進(jìn)行遍歷。
SelectSingleNode只返回第一個(gè)符合xpath表達(dá)式的節(jié)點(diǎn),或者返回null。
以下面的XML文件為例,我們進(jìn)行一些演示:
<?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é)點(diǎn):
XmlNodeList nodelist = xmlDoc.SelectNodes("/Customers/Customer/Contact");
foreach (XmlNode node in nodelist)
{
Console.WriteLine(node.OuterXml);
}
輸出結(jié)果為:
<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);
輸出結(jié)果為:
<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);
輸出結(jié)果:
<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);
輸出結(jié)果:
<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");
總結(jié): XmlDocument類是.Net API中提供的支持W3C XML DOM標(biāo)準(zhǔn)的類??梢杂盟鼇韯?chuàng)建和查詢XML文檔。由于XmlDocument要將XML文檔的內(nèi)容全部裝載進(jìn)內(nèi)存中,所以對(duì)于讀取內(nèi)容過大的XML文檔,不適合使用XmlDocument類,而可以使用XmlReader來完成讀取。
(一) 加載
加載XML比較常用的有三種方法:
public virtual void Load(string filename);
public virtual void Load(Stream inStream);
public virtual void LoadXml(string xml);
下面代碼演示如何使用它們:
復(fù)制代碼 代碼如下:
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);
(二) 查詢
對(duì)XML的元素、屬性、文本的查詢可以使用XPath。具體的定義可以參看w3school。
首先應(yīng)該了解一下XPath表達(dá)式:
表達(dá)式 | 描述 |
nodename | 選取此節(jié)點(diǎn)的所有子節(jié)點(diǎn)。 |
/ | 從根節(jié)點(diǎn)選取。 |
// | 從匹配選擇的當(dāng)前節(jié)點(diǎn)選擇文檔中的節(jié)點(diǎn),而不考慮它們的位置。 |
. | 選取當(dāng)前節(jié)點(diǎn)。 |
.. | 選取當(dāng)前節(jié)點(diǎn)的父節(jié)點(diǎn)。 |
@ | 選取屬性。 |
我們主要使用兩個(gè)方法來查詢XML文檔,SelectNodes(xpath expression)和SelectSingleNode(xpath expression)。
SelectNodes返回一個(gè)XmlNodeList對(duì)象,也就是所有符合xpath表達(dá)式的xml節(jié)點(diǎn)都將會(huì)被返回,你需要對(duì)返回的結(jié)果進(jìn)行遍歷。
SelectSingleNode只返回第一個(gè)符合xpath表達(dá)式的節(jié)點(diǎn),或者返回null。
以下面的XML文件為例,我們進(jìn)行一些演示:
復(fù)制代碼 代碼如下:
<?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é)點(diǎn):
XmlNodeList nodelist = xmlDoc.SelectNodes("/Customers/Customer/Contact");
foreach (XmlNode node in nodelist)
{
Console.WriteLine(node.OuterXml);
}
輸出結(jié)果為:
<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);
輸出結(jié)果為:
<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);
輸出結(jié)果:
<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);
輸出結(jié)果:
<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文檔為例:
復(fù)制代碼 代碼如下:
<?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>
復(fù)制代碼 代碼如下:
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");
總結(jié): XmlDocument類是.Net API中提供的支持W3C XML DOM標(biāo)準(zhǔn)的類??梢杂盟鼇韯?chuàng)建和查詢XML文檔。由于XmlDocument要將XML文檔的內(nèi)容全部裝載進(jìn)內(nèi)存中,所以對(duì)于讀取內(nèi)容過大的XML文檔,不適合使用XmlDocument類,而可以使用XmlReader來完成讀取。
相關(guān)文章
c# 多線程環(huán)境下控制對(duì)共享資源訪問的解決方法
這篇文章主要介紹了c# 多線程環(huán)境下控制對(duì)共享資源訪問的解決方法,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2024-07-07C# Fiddler插件實(shí)現(xiàn)網(wǎng)站離線瀏覽功能
本文主要介紹了C# Fiddler插件實(shí)現(xiàn)網(wǎng)站離線瀏覽功能的原理與方法。具有很好的參考價(jià)值,下面跟著小編一起來看下吧2017-02-02C#之Windows自帶打印功能的實(shí)現(xiàn)
這篇文章主要介紹了C#之Windows自帶打印功能的實(shí)現(xiàn)方式,具有很好的價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06