位置:首頁 > 軟件操作教程 > 編程開發(fā) > C# > 問題詳情

C# LINQtoXML函數(shù)構(gòu)造方式

提問人:劉團(tuán)圓發(fā)布時間:2020-12-10

    可在代碼中用XMLDOM創(chuàng)建XML文擋,而LINQ to XML提供了一種更便捷的方式,稱為函數(shù)構(gòu)造方式(functional construction)。在這種方式中,構(gòu)造函數(shù)的調(diào)用可以用反映;XML文檔結(jié)構(gòu)的方式嵌套。下面的示例就使用函數(shù)構(gòu)造方式建立了一個包含顧客和訂單的簡單XML文檔。


試一試 LINQ to XML: BeginningCSharp7_22_1 _LinqToXmlConstructors

按照下面的步驟在Visual Studio 2017中創(chuàng)建示例:

(1)在 C:\BeginningCShaip7\Chapter22目錄中創(chuàng)建一個新的控制臺應(yīng)用程序 BeginningCSharp7_22_l LinqToXml Constructors。

(2)打開主源文件Program.cs。

(3)在Program.cs的開頭處添加對System.XmLLinq名稱空間的引用,如下所示:

using System;

using System.Collections,Generic;

using System.Linq;

using System.Xml.Linq;

using System.Text;

using static System.Console;

(4)在Program.es的Main()方法中添加如下代碼:

static void Main{string[] args)

{

        XDocument xdoc = new XDocument( 

            new XElement ("customers", 

                new XElement("customer",

                    new XAttribute("ID", "A"),

                    new XAttribute("City", "New York"),

                    new XAttribute("Region", "North America"),

                    new XElement("order",

                        new XAttribute("Item", "Widget"), 

                        new XAttribute("Price", 100)

                    )

                    new XElement("order",

                        new XAttribute T'Item", "Tire"), 

                        new XAttribute("Price", 220)

                    )

                ),    

                new XElement("customer",

                    new XAttribute ("ID", "B"), 

                    new XAttribute ("City" r "Mumbai"), 

                    new XAttribute ("Region" , "Asia"), 

                    new XElement("order",

                        new XAttribute ("Item","Oven"), 

                        new XAttribute("Price", 501)

                    )

                )

            )

        );

        WriteLine(xdoc);

        Write("Program finished, press Enter/Return to continue:"); 

        ReadLine();

}

(5)編譯并執(zhí)行程序(按下F5鍵即可開始調(diào)試),輸出結(jié)果如下所示:

<customers>

  <customer ID="A" City="New York" Region="North America"〉

    <order Item="Widget" Price="100" />

    <order Item="Tire" Price="200" />

  </customer>

  <customer ID="B" City="Mumbai" Region="Asia">

    <order Item="Oven" Price="501" />

  </customer>

</customers>

Program finished, press Enter/Return to continue:

    在輸出屏幕上顯示的XML文檔包含前面示例中顧客/訂單數(shù)據(jù)的一個簡化版本。注意,XML文檔的根元素是<customers>,它包含兩個嵌套的<customer>元素,這兩個元素又包含許多嵌套的<order>元素。<customer>元素具有兩個特性:City和Region,<order>元素也有兩個特性:Item和Price。

    按下Enter/Retum鍵,退出程序,關(guān)閉控制臺屏幕。如果使用Ctrl+F5組合鍵(啟動時不使用調(diào)試功能),就需要按Enter/Retum鍵兩次。


示例說明

第一步是引用System.Xml.Linq名稱空間。本章的所有XML示例都要求把這行代碼添加到程序中:

    using System.Xml.Linq;

在創(chuàng)建項(xiàng)目時,System.Linq名稱空間是默認(rèn)包含的,但不包含System.XmLLinq名稱空間,所以必須顯式地添加這行代碼。

接著調(diào)用LINQtoXML構(gòu)造函數(shù)XDocument()、XElement()和XAttribute(),它們彼此嵌套,如下所示:

    XDocument xdoc = new XDocument{ 

        new XElement("customers", 

            new XElement("customer",

                new XAttribute("ID", "A"),

                ...

注意,這些代碼看起來類似于XML本身,即文檔包含元素,每個元素又包含特性和其他元素。下面依次分析這些構(gòu)造函數(shù):

? XDocument():在LINQ to XML構(gòu)造函數(shù)層次結(jié)構(gòu)中,最高層的對象是XDocument(),它表示完整的XML文檔,在代碼中如下所示:

static void Main(string[] args)

{

        XDocument xdoc = new XDocument(

...

        };

    在前面的代碼段中,省略了XDocumentO的參數(shù)列表,因此可以看到XDocument()調(diào)用在何處開始和結(jié)束。與所有LINQtoXML構(gòu)造函數(shù)一樣,XDocument()也把對象數(shù)組(object[])作為它的參數(shù)之一,以便給它傳遞其他構(gòu)造函數(shù)創(chuàng)建的其他多個對象。在這個程序中調(diào)用的所有其他構(gòu)造函數(shù)都是XDocument()構(gòu)造函數(shù)的參數(shù)。這個程序傳遞的第一個也是唯一一個參數(shù)是XElement()構(gòu)造函數(shù)。

? XElement(): XML文檔必須有一個根元素,所以大多數(shù)情況下,XDocumentO的參數(shù)列表都以一個XElement對象開頭。XElementO構(gòu)造函數(shù)把元素名作為字符串,其后是包含在該元素中的一個XML對象列表。本例中的根元素是customers,它又包含一個customer元素列表:

    new XElement("customers",

        new XElement("customer",

...

        ),

...

        )

customer元素不包含其他XML元素,只包含3個XML特性,它們用XAttribute()構(gòu)造函數(shù)構(gòu)建。

  ? XAttribute():這里給 customer 元素添加了 3個 XML特性:ID、City 和 Region:

    new XAttribute("ID", "A"),

    new XAttribute("City", "New York"),

    new XAttribute("Region", "North America"),

根據(jù)定義,XML特性是一個XML葉節(jié)點(diǎn),它不包含其他XML節(jié)點(diǎn),所以XAttributeQ構(gòu)造函數(shù)的參數(shù)只有特性的名稱和值。本例中生成的3個特性是ID="A"、City="New York"和Region="North America"。

  ?其他LINQ to XML構(gòu)造函數(shù):這個程序中沒有調(diào)用它們,但所有XML節(jié)點(diǎn)類型都有其他LINQto XML構(gòu)造函數(shù),例如,XDedarationO用于XML文檔開頭的XML聲明,XComment()用于XML注釋等。這些構(gòu)造函數(shù)不太常用,但如果需要它們來精確控制XML文檔的格式化,就可以使用它們。

下面繼續(xù)解釋第一個示例:在customer元素的ID, City和Region特性后面再添加兩個子order元素:

    new XElement ("order='r/

        new XAttribute("Item" "Widget"),

        new XAttribute("Price", 100)

    ),

    new XElement ("order",

        new XAttribute("Item", "Tire"), 

        new XAttribute("Price", 200)

    )

這些order元素都有兩個特性:Item和Price,但沒有子元素。

接著將XDocument的內(nèi)容顯示在控制臺屏幕上:

    WriteLine(xdoc);

這行代碼使用XDociimentO的默認(rèn)方法ToString()輸出XML文擋的文本。

最后暫停屏幕,以便查看控制臺輸出,再等待用戶按下回車鍵:

    Write("Program finished, press Enter/Return to continue:");

    ReadLine();

程序退出Main()方法后,就結(jié)束程序。

繼續(xù)查找其他問題的答案?

相關(guān)視頻回答
回復(fù)(0)
返回頂部