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

來源:互聯網
上載者:User

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" 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節點:
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的區別:
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);
(三) 建立
以建立以下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標準的類。可以用它來建立和查詢XML文檔。由於XmlDocument要將XML文檔的內容全部裝載進記憶體中,所以對於讀取內容過大的XML文檔,不適合使用XmlDocument類,而可以使用XmlReader來完成讀取。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.