這篇文章給大家分享的是有關(guān)如何使用LINQ to XML創(chuàng)建xml的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過來看看吧。
創(chuàng)新互聯(lián)建站成立于2013年,我們提供高端成都網(wǎng)站建設(shè)、網(wǎng)站制作、成都網(wǎng)站設(shè)計(jì)、網(wǎng)站定制、成都全網(wǎng)營銷、微信小程序開發(fā)、微信公眾號(hào)開發(fā)、seo優(yōu)化服務(wù),提供專業(yè)營銷思路、內(nèi)容策劃、視覺設(shè)計(jì)、程序開發(fā)來完成項(xiàng)目落地,為公路鉆孔機(jī)企業(yè)提供源源不斷的流量和訂單咨詢。
以下的代碼演示了如何使用LINQ to XML來快速創(chuàng)建一個(gè)xml:
隱藏行號(hào) 復(fù)制代碼 ?創(chuàng)建 XML
public static void CreateDocument() { string path = @"d:\website"; XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), new XElement("Root", "root")); xdoc.Save(path); }
運(yùn)行該示例將會(huì)得到一個(gè)xml文件,其內(nèi)容為:
<?xml version="1.0" encoding="utf-8" standalone="yes"?> <Root>root</Root>
XElement 類是 LINQ to XML 中的基礎(chǔ)類之一。 它表示一個(gè) XML 元素。 可以使用該類創(chuàng)建元素;更改元素內(nèi)容;添加、更改或刪除子元素;向元素中添加屬性;或以文本格式序列化元素內(nèi)容。 還可以與 System.Xml 中的其他類(例如 XmlReader、XmlWriter 和 XslCompiledTransform)進(jìn)行互操作。
使用LINQ to XML創(chuàng)建xml文檔有很多種方式,具體使用哪種方法要根據(jù)實(shí)際需要。而創(chuàng)建xml文檔最簡單、最常見的方式是使用XElement類。以下的代碼演示了如何使用XElement類創(chuàng)建一個(gè)xml文檔:
顯示行號(hào) 復(fù)制代碼 ?這是一段程序代碼。
public static void CreateCategories() { string path = @"d:\website"; XElement root = new XElement("Categories", new XElement("Category", new XElement("CategoryID", Guid.NewGuid()), new XElement("CategoryName", "Beverages") ), new XElement("Category", new XElement("CategoryID", Guid.NewGuid()), new XElement("CategoryName", "Condiments") ), new XElement("Category", new XElement("CategoryID", Guid.NewGuid()), new XElement("CategoryName", "Confections") ) ); root.Save(path); }
運(yùn)行該示例將會(huì)得到一個(gè)xml文件,其內(nèi)容為:
<?xml version="1.0" encoding="utf-8"?> <Categories> <Category> <CategoryID>57485174-46fc-4e8c-8d98-d25b53d504a1</CategoryID> <CategoryName>Beverages</CategoryName> </Category> <Category> <CategoryID>1474dde1-8014-48f7-b093-b47ca5d5b770</CategoryID> <CategoryName>Condiments</CategoryName> </Category> <Category> <CategoryID>364224e0-e002-4939-90fc-0fd93e0cf35b</CategoryID> <CategoryName>Confections</CategoryName> </Category> </Categories>
XElement類包含了許多方法,這些方法使得處理xml變得輕而易舉。有關(guān)這些方法請參照MSDN。
其中,Save、CreateReader、ToString和WriteTo方法是比較常用的三個(gè)方法:
XAttribute類用來處理元素的屬性,屬性是與元素相關(guān)聯(lián)的“名稱-值”對,每個(gè)元素中不能有名稱重復(fù)的屬性。使用XAttribute類與使用XElement類的操作十分相似,下面的示例演示了如何在創(chuàng)建xml樹時(shí)為其添加一個(gè)屬性:
顯示行號(hào) 復(fù)制代碼 ?這是一段程序代碼。
public static XElement CreateCategoriesByXAttribute() { XElement root = new XElement("Categories", new XElement("Category", new XAttribute("CategoryID", Guid.NewGuid()), new XElement("CategoryName", "Beverages") ), new XElement("Category", new XAttribute("CategoryID", Guid.NewGuid()), new XElement("CategoryName", "Condiments") ), new XElement("Category", new XAttribute("CategoryID", Guid.NewGuid()), new XElement("CategoryName", "Confections") ) ); root.Save(path); return root; }
運(yùn)行該示例將會(huì)得到一個(gè)xml文件,其內(nèi)容為:
<?xml version="1.0" encoding="utf-8"?> <Categories> <Category CategoryID="a6d5ef04-3f83-4e00-aeaf-52444add7570"> <CategoryName>Beverages</CategoryName> </Category> <Category CategoryID="67a168d5-6b22-4d82-9bd4-67bec88c2ccb"> <CategoryName>Condiments</CategoryName> </Category> <Category CategoryID="17398f4e-5ef1-48da-8a72-1c54371b8e76"> <CategoryName>Confections</CategoryName> </Category> </Categories>
XAttribute類的方法比較少,常用的三個(gè)是:
以下的示例使用Remove來刪除第一個(gè)元素的CategoryID屬性:
顯示行號(hào) 復(fù)制代碼 ?這是一段程序代碼。
public static void RemoveAttribute() { XElement xdoc = CreateCategoriesByXAttribute(); XAttribute xattr = xdoc.Element("Category").Attribute("CategoryID"); xattr.Remove(); xdoc.Save(path); }
運(yùn)行該示例將會(huì)得到一個(gè)xml文件,其內(nèi)容為:
<?xml version="1.0" encoding="utf-8"?> <Categories> <Category> <CategoryName>Beverages</CategoryName> </Category> <Category CategoryID="5c311c1e-ede5-41e5-93f7-5d8b1d7a0346"> <CategoryName>Condiments</CategoryName> </Category> <Category CategoryID="bfde8db5-df84-4415-b297-cd04d8db9712"> <CategoryName>Confections</CategoryName> </Category> </Categories>
作為嘗試,試一試以下刪除屬性的方法:
public static void RemoveAttributeByDoc() { XElement xdoc = CreateCategoriesByXAttribute(); XAttribute xattr = xdoc.Attribute("CategoryID"); xattr.Remove(); xdoc.Save(path); }
運(yùn)行該示例將會(huì)拋出一個(gè)空引用異常,因?yàn)樵谻ategories沒有一個(gè)叫做CategoryID的屬性。
XDocument類提供了處理xml文檔的方法,包括聲明、注釋和處理指令。一個(gè)XDocument對象可以包含以下內(nèi)容:
下面的示例創(chuàng)建了一個(gè)簡單的xml文檔,它包含幾個(gè)元素和一個(gè)屬性,以及一個(gè)處理指令和一些注釋:
public static void CreateXDocument() { XDocument xdoc = new XDocument( new XProcessingInstruction("xml-stylesheet", "title='EmpInfo'"), new XComment("some comments"), new XElement("Root", new XElement("Employees", new XElement("Employee", new XAttribute("id", "1"), new XElement("Name", "Scott Klein"), new XElement("Title", "Geek"), new XElement("HireDate", "02/05/2007"), new XElement("Gender", "M") ) ) ), new XComment("more comments") ); xdoc.Save(path); }
運(yùn)行該示例將會(huì)得到一個(gè)xml文件,其內(nèi)容為:
<?xml version="1.0" encoding="utf-8"?> <?xml-stylesheet title='EmpInfo'?> <!--some comments--> <Root> <Employees> <Employee id="1"> <Name>Scott Klein</Name> <Title>Geek</Title> <HireDate>02/05/2007</HireDate> <Gender>M</Gender> </Employee> </Employees> </Root> <!--more comments-->
XDocument類包含多個(gè)與XElement類相同的方法,具體內(nèi)容可以參閱MSDN。需要注意的是,處理節(jié)點(diǎn)和元素的大部分功能都可以通過XElement獲得,只有當(dāng)絕對需要文檔層次的處理能力,以及需要訪問注釋、處理指令和聲明時(shí),才有使用XDocument類的必要。
創(chuàng)建了xml文檔后,可以使用NodesAfterSelf方法返回指定的XElement元素之后的所有同級元素。需要注意的是,此方法只包括返回集合中的同級元素,而不包括子代。此方法使用延遲執(zhí)行。以下代碼演示了這一過程:
顯示行號(hào) 復(fù)制代碼 ?這是一段程序代碼。
public static void NodesAfterSelf() { XElement root = new XElement("Categories", new XElement("Category", new XElement("CategoryID", Guid.NewGuid()), new XElement("CategoryName", "食品"), new XElement("Description", "可以吃的東西") ) ); foreach (var item in root.Element("Category").Element("CategoryID").NodesAfterSelf()) { Console.WriteLine((item as XElement).Value); } }
本節(jié)將介紹LINQ to XML編程的相關(guān)概念,例如如何加載xml、創(chuàng)建全新xml、操縱xml的信息以及遍歷xml文檔。
使用LINQ to XML加載xml可以從多種數(shù)據(jù)源獲得,例如字符串、XmlReader、TextReader或文件。
下面的示例演示了如何從文件中加載xml:
public static void LoadFromFile() { XElement root = XElement.Load(path); Console.WriteLi
也可以使用Parse方法從一個(gè)字符串加載xml:
public static void LoadFromString() { XElement root = XElement.Parse(@" <Categories> <Category> <CategoryID>1</CategoryID> <CategoryName>Beverages</CategoryName> <Description>Soft drinks, coffees, teas, beers, and ales</Description> </Category> </Categories> "); Console.WriteLine(root.ToString()); }
在前面的示例中曾多次調(diào)用XElement對象的Save方法來保存xml文檔,在這里就不冗述了。
在前面的示例中曾多次調(diào)用XElement對象的構(gòu)造函數(shù)來創(chuàng)建xml文檔,在這里就不冗述了。需要說明的是,在使用LINQ to XML創(chuàng)建xml文檔時(shí),會(huì)有代碼縮進(jìn),這使代碼的可讀性大大加強(qiáng)。
使用LINQ to XML在xml樹中遍歷xml是相當(dāng)簡單的。只需要使用XElement和XAttribute類中所提供的方法。Elements和Element方法提供了定位到某個(gè)或某些元素的方式。下面的示例演示了如何遍歷xml樹,并獲取指定元素的方式:
public static void Enum() { XElement root = new XElement("Categories"); using (NorthwindDataContext db = new NorthwindDataContext()) { root.Add( db.Categories .Select ( c => new XElement ( "Category" , new XElement("CategoryName", c.CategoryName) ) ) ); } foreach (var item in root.Elements("Category")) { Console.WriteLine(item.Element("CategoryName").Value); } }
上述代碼運(yùn)行的結(jié)果為:
是不是很簡單呢?Nodes()、Elements()、Element(name)和Elements(name)方法為xml樹的導(dǎo)航提供了基本功能。
LINQ to XML一個(gè)重要的特性是能夠方便地修改xml樹,如添加、刪除、更新和復(fù)制xml文檔的內(nèi)容。
I.插入
使用XNode類的插入方法可以方便地向xml樹添加內(nèi)容:
在下面的示例中,使用AddAfterSelf方法向現(xiàn)有xml中添加一個(gè)新節(jié)點(diǎn):
public static void AddAfterSelf() { XElement root = XElement.Parse(@" <Categories> <Category> <CategoryID>1</CategoryID> <CategoryName>Beverages</CategoryName> <Description>Soft drinks, coffees, teas, beers, and ales</Description> </Category> </Categories> "); XElement xele = root.Element("Category").Element("CategoryName"); xele.AddAfterSelf(new XElement("AddDate", DateTime.Now)); root.Save(path); }
運(yùn)行該示例將會(huì)得到一個(gè)xml文件,其內(nèi)容為:
<?xml version="1.0" encoding="utf-8"?> <Categories> <Category> <CategoryID>1</CategoryID> <CategoryName>Beverages</CategoryName> <AddDate>2010-01-31T03:08:51.813736+08:00</AddDate> <Description>Soft drinks, coffees, teas, beers, and ales</Description> </Category> </Categories>
當(dāng)需要添加一個(gè)元素到指定節(jié)點(diǎn)之前時(shí),可以使用AddBeforeSelf方法。
II.更新
在LINQ to XML中更新xml內(nèi)容可以使用以下幾種方法:
在下面的示例中使用了ReplaceWith與SetElementValue方法對xml進(jìn)行了更新操作:
public static void Update() { XElement root = XElement.Parse(@" <Categories> <Category> <CategoryID>1</CategoryID> <CategoryName>Beverages</CategoryName> <Description>Soft drinks, coffees, teas, beers, and ales</Description> </Category> </Categories> "); root.Element("Category").Element("CategoryID").ReplaceWith(new XElement("ID", "2")); root.Element("Category").SetElementValue("CategoryName", "test data"); root.Save(path); }
運(yùn)行該示例將會(huì)得到一個(gè)xml文件,其內(nèi)容為:
<?xml version="1.0" encoding="utf-8"?> <Categories> <Category> <ID>2</ID> <CategoryName>test data</CategoryName> <Description>Soft drinks, coffees, teas, beers, and ales</Description> </Category> </Categories>
III.刪除
可以使用Remove(XElement)與RemoveAll方法來刪除xml。
在下面的示例中,使用了RemoveAll方法:
} public static void Remove() { string path = @"d:\"; XElement root = XElement.Parse(@" <Categories> <Category> <CategoryID>1</CategoryID> <CategoryName>Beverages</CategoryName> <Description>Soft drinks, coffees, teas, beers, and ales</Description> </Category> </Categories> "); root.RemoveAll(); root.Save(path); }
運(yùn)行該示例將會(huì)得到一個(gè)xml文件,其內(nèi)容為:
<?xml version="1.0" encoding="utf-8"?> <Categories />
在下面的示例中,使用了Remove方法刪除了xml的Description元素:
public static void Remove() { XElement root = XElement.Parse(@" <Categories> <Category> <CategoryID>1</CategoryID> <CategoryName>Beverages</CategoryName> <Description>Soft drinks, coffees, teas, beers, and ales</Description> </Category> </Categories> "); root.Element("Category").Element("Description").Remove(); root.Save(path); }
運(yùn)行該示例將會(huì)得到一個(gè)xml文件,其內(nèi)容為:
<?xml version="1.0" encoding="utf-8"?> <Categories> <Category> <CategoryID>1</CategoryID> <CategoryName>Beverages</CategoryName> </Category> </Categories>
I.添加
LINQ to XML添加屬性與添加元素師類似的,可以使用構(gòu)造函數(shù)或者Add方法來添加屬性:
public static void AddAttribute() { XElement root = new XElement("Categories", new XElement("Category", new XAttribute("CategoryID", "1"), new XElement("CategoryName", "Beverages"), new XElement("Description", "Soft drinks, coffees, teas, beers, and ales") ) ); root.Element("Category").Add(new XAttribute("AddDate", DateTime.Now.ToShortDateString())); root.Save(path); }
運(yùn)行該示例將會(huì)得到一個(gè)xml文件,其內(nèi)容為:
<?xml version="1.0" encoding="utf-8"?> <Categories> <Category CategoryID="1" AddDate="2010-01-31"> <CategoryName>Beverages</CategoryName> <Description>Soft drinks, coffees, teas, beers, and ales</Description> </Category> </Categories>
II.檢索
檢索屬性可以使用Attribute(name)方法:
顯示行號(hào) 復(fù)制代碼 ?這是一段程序代碼。
public static void SelectAttribute() { XElement root = new XElement("Categories", new XElement("Category", new XAttribute("CategoryID", "1"), new XElement("CategoryName", "Beverages"), new XElement("Description", "Soft drinks, coffees, teas, beers, and ales") ) ); XAttribute xattr = root.Element("Category").Attribute("CategoryID"); Console.WriteLine(xattr.Name); Console.WriteLine(xattr.Value); }
上述代碼的運(yùn)行結(jié)果為:
CategoryID 1
感謝各位的閱讀!關(guān)于“如何使用LINQ to XML創(chuàng)建xml”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!
分享名稱:如何使用LINQtoXML創(chuàng)建xml
本文URL:http://www.chinadenli.net/article16/pidpdg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供搜索引擎優(yōu)化、微信公眾號(hào)、網(wǎng)站導(dǎo)航、標(biāo)簽優(yōu)化、網(wǎng)站制作、做網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)