目錄
 
1、LINQ to XML類別
2、XElement類別
3、XAttribute類別 
4、XDocument類別
二、LINQ to XML程式設計概念
1、加载已有的xml
2、保存xml
3、创建xml
4、遍历xml
5、操纵xml
6、处理属性
本文总结
首頁 後端開發 XML/RSS教程 LINQ to XML 程式設計基礎的圖文程式碼詳細介紹

LINQ to XML 程式設計基礎的圖文程式碼詳細介紹

Mar 07, 2017 pm 04:55 PM

 

1、LINQ to XML類別

 

LINQ to XML 程式設計基礎的圖文程式碼詳細介紹

以下的程式碼示範如何使用LINQ to XML來快速建立一個xml:


隱藏行號 複製程式碼 創建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);
}
登入後複製

運行該範例將會得到一個xml文件,其內容為:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Root>root</Root>
登入後複製

2、XElement類別

XElement 類別是LINQ to XML 中的基礎類別之一。 它表示一個 XML 元素。 可以使用該類別建立元素;更改元素內容;新增​​、變更或刪除子元素;在元素中新增屬性;或以文字格式序列化元素內容。 也可以與 System.Xml 中的其他類別(例如 XmlReader、XmlWriter 和 XslCompiledTransform)進行互通。

使用LINQ to XML建立xml文件有很多種方式,具體使用哪一種方法要根據實際需求。而創建xml文檔最簡單、最常見的方式就是使用XElement類別。以下的程式碼示範如何使用XElement類別建立一個xml文件:

 顯示行號 複製程式碼 這是一段程式碼。

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);

}
登入後複製

執行此範例將會得到一個xml文件,其內容為:

<?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變得輕而易舉。有關這些方法請參考MSDN。

其中,Save、CreateReader、ToString和WriteTo方法是比較常用的三個方法:

LINQ to XML 程式設計基礎的圖文程式碼詳細介紹

 

3、XAttribute類別 

XAttribute類別用來處理元素的屬性,屬性是與元素相關聯的「名稱-值」對,每個元素中不能有名稱重複的屬性。使用XAttribute類別與使用XElement類別的操作十分相似,下面的範例示範如何在建立xml樹時為其新增一個屬性:

顯示行號 複製程式碼 這是一段程式碼。

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;
}
登入後複製

運行該範例將會得到一個xml文件,其內容為:

<?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類的方法比較少,常用的三個是:

LINQ to XML 程式設計基礎的圖文程式碼詳細介紹

以下的範例使用Remove來刪除第一個元素的CategoryID屬性:

#顯示行號 複製程式碼 這是一段程式碼。

public static void RemoveAttribute()
{

    XElement xdoc = CreateCategoriesByXAttribute();

    XAttribute xattr = xdoc.Element("Category").Attribute("CategoryID");

    xattr.Remove();

    xdoc.Save(path);

}
登入後複製

執行此範例將會得到一個xml文件,其內容為:

<?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);

}
登入後複製

執行此範例將會拋出一個空引用異常,因為元素Categories沒有一個叫做CategoryID的屬性。

4、XDocument類別

 

XDocument類別提供了處理xml文件的方法,包括宣告、註解和處理指令。一個XDocument物件可以包含以下內容:

LINQ to XML 程式設計基礎的圖文程式碼詳細介紹

下面的範例創建了一個簡單的xml文檔,它包含幾個元素和一個屬性,以及一個處理指令和一些註釋:

public static void CreateXDocument()
      {

          XDocument xdoc = new XDocument(

                  new XProcessingInstruction("xml-stylesheet", "title=&#39;EmpInfo&#39;"),

                  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);

      }
登入後複製


執行範例將會得到一個xml文件,其內容為:

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet title=&#39;EmpInfo&#39;?>
<!--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類別包含多個與XElement類別相同的方法,具體內容可以參閱MSDN。要注意的是,處理節點和元素的大部分功能都可以透過XElement取得,只有當絕對需要文件層次的處理能力,以及需要存取註解、處理指令和聲明時,才有使用XDocument類別的必要。

建立了xml文件後,可以使用NodesAfterSelf方法傳回指定的XElement元素之後的所有同級元素。需要注意的是,此方法只包括傳回集合中的同級元素,而不包括子代。此方法使用延遲執行。以下程式碼示範了這個過程:

顯示行號 複製程式碼 這是一段程式碼。

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);
    }
}
登入後複製

 

二、LINQ to XML程式設計概念

 

本節將介紹LINQ to XML程式設計的相關概念,例如如何載入xml、創建全新xml、操縱xml的資訊以及遍歷xml文件。

 

1、加载已有的xml

使用LINQ to XML加载xml可以从多种数据源获得,例如字符串、XmlReader、TextReader或文件。

下面的示例演示了如何从文件中加载xml:

public static void LoadFromFile()
{

    XElement root = XElement.Load(path);

    Console.WriteLi
登入後複製


也可以使用Parse方法从一个字符串加载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());

    }
登入後複製

2、保存xml

在前面的示例中曾多次调用XElement对象的Save方法来保存xml文档,在这里就不冗述了。

3、创建xml

在前面的示例中曾多次调用XElement对象的构造函数来创建xml文档,在这里就不冗述了。需要说明的是,在使用LINQ to XML创建xml文档时,会有代码缩进,这使代码的可读性大大加强。

4、遍历xml

使用LINQ to XML在xml树中遍历xml是相当简单的。只需要使用XElement和XAttribute类中所提供的方法。Elements和Element方法提供了定位到某个或某些元素的方式。下面的示例演示了如何遍历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);

    }

}
登入後複製

上述代码运行的结果为:

LINQ to XML 程式設計基礎的圖文程式碼詳細介紹

是不是很简单呢?Nodes()、Elements()、Element(name)和Elements(name)方法为xml树的导航提供了基本功能。

5、操纵xml

LINQ to XML一个重要的特性是能够方便地修改xml树,如添加、删除、更新和复制xml文档的内容。

I.插入

使用XNode类的插入方法可以方便地向xml树添加内容:

LINQ to XML 程式設計基礎的圖文程式碼詳細介紹

在下面的示例中,使用AddAfterSelf方法向现有xml中添加一个新节点:

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);

}
登入後複製

运行该示例将会得到一个xml文件,其内容为:

<?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>
登入後複製

当需要添加一个元素到指定节点之前时,可以使用AddBeforeSelf方法。

II.更新

在LINQ to XML中更新xml内容可以使用以下几种方法:

LINQ to XML 程式設計基礎的圖文程式碼詳細介紹

在下面的示例中使用了ReplaceWith与SetElementValue方法对xml进行了更新操作:

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);
}
登入後複製

运行该示例将会得到一个xml文件,其内容为:

<?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);

  }
登入後複製

运行该示例将会得到一个xml文件,其内容为:

<?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);
}
登入後複製

运行该示例将会得到一个xml文件,其内容为:

<?xml version="1.0" encoding="utf-8"?>

<Categories>

  <Category>

    <CategoryID>1</CategoryID>

    <CategoryName>Beverages</CategoryName>

  </Category>

</Categories>
登入後複製

6、处理属性

I.添加

LINQ to XML添加属性与添加元素师类似的,可以使用构造函数或者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);
}
登入後複製

运行该示例将会得到一个xml文件,其内容为:

<?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)方法:

显示行号 复制代码 这是一段程序代码。

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);
}
登入後複製

上述代码的运行结果为:

CategoryID
1
登入後複製

本文总结

本文介绍了LINQ to XML的编程基础,即System.Xml.Linq命名空间中的多个LINQ to XML类,这些类都是LINQ to XML的支持类,它们使得处理xml比使用其他的xml工具容易得多。在本文中,着重介绍的是XElement、XAttribute和XDocument。 

 以上就是LINQ to XML 编程基础的图文代码详细介绍的内容,更多相关内容请关注PHP中文网(www.php.cn)!


本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
4 週前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
4 週前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
4 週前 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
1 個月前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

能否用PowerPoint開啟XML文件 能否用PowerPoint開啟XML文件 Feb 19, 2024 pm 09:06 PM

XML檔可以用PPT開啟嗎? XML,即可擴展標記語言(ExtensibleMarkupLanguage),是一種廣泛應用於資料交換和資料儲存的通用標記語言。與HTML相比,XML更加靈活,能夠定義自己的標籤和資料結構,使得資料的儲存和交換更加方便和統一。而PPT,即PowerPoint,是微軟公司開發的一種用於創建簡報的軟體。它提供了圖文並茂的方

使用Python實現XML資料的合併與去重 使用Python實現XML資料的合併與去重 Aug 07, 2023 am 11:33 AM

使用Python實現XML資料的合併和去重XML(eXtensibleMarkupLanguage)是一種用於儲存和傳輸資料的標記語言。在處理XML資料時,有時候我們需要將多個XML檔案合併成一個,或移除重複的資料。本文將介紹如何使用Python實現XML資料的合併和去重的方法,並給出對應的程式碼範例。一、XML資料合併當我們有多個XML文件,需要將其合

使用Python實現XML資料的篩選和排序 使用Python實現XML資料的篩選和排序 Aug 07, 2023 pm 04:17 PM

使用Python實現XML資料的篩選和排序引言:XML是一種常用的資料交換格式,它以標籤和屬性的形式儲存資料。在處理XML資料時,我們經常需要對資料進行篩選和排序。 Python提供了許多有用的工具和函式庫來處理XML數據,本文將介紹如何使用Python實現XML資料的篩選和排序。讀取XML檔案在開始之前,我們需要先讀取XML檔案。 Python有許多XML處理函式庫,

Python中的XML資料轉換為CSV格式 Python中的XML資料轉換為CSV格式 Aug 11, 2023 pm 07:41 PM

Python中的XML資料轉換為CSV格式XML(ExtensibleMarkupLanguage)是一種可擴充標記語言,常用於資料的儲存與傳輸。而CSV(CommaSeparatedValues)則是一種以逗號分隔的文字檔案格式,常用於資料的匯入和匯出。在處理資料時,有時需要將XML資料轉換為CSV格式以便於分析和處理。 Python作為一種功能強大

使用PHP將XML資料匯入資料庫 使用PHP將XML資料匯入資料庫 Aug 07, 2023 am 09:58 AM

使用PHP將XML資料匯入資料庫引言:在開發中,我們經常需要將外部資料匯入到資料庫中進行進一步的處理和分析。而XML作為一種常用的資料交換格式,也常被用來儲存和傳輸結構化資料。本文將介紹如何使用PHP將XML資料匯入資料庫。步驟一:解析XML文件首先,我們需要解析XML文件,擷取所需的資料。 PHP提供了幾種解析XML的方式,其中最常用的是使用Simple

Python實作XML與JSON之間的轉換 Python實作XML與JSON之間的轉換 Aug 07, 2023 pm 07:10 PM

Python實作XML與JSON之間的轉換導語:在日常的開發過程中,我們常常需要將資料在不同的格式之間轉換。 XML和JSON是常見的資料交換格式,在Python中,我們可以使用各種函式庫來實作XML和JSON之間的相互轉換。本文將介紹幾種常用的方法,並附帶程式碼範例。一、XML轉JSON在Python中,我們可以使用xml.etree.ElementTree模

使用Python處理XML中的錯誤和異常 使用Python處理XML中的錯誤和異常 Aug 08, 2023 pm 12:25 PM

使用Python處理XML中的錯誤和異常XML是一種常用的資料格式,用於儲存和表示結構化的資料。當我們使用Python處理XML時,有時可能會遇到一些錯誤和異常。在本篇文章中,我將介紹如何使用Python來處理XML中的錯誤和異常,並提供一些範例程式碼供參考。使用try-except語句捕捉XML解析錯誤當我們使用Python解析XML時,有時候可能會遇到一些

Python解析XML中的特殊字元和轉義序列 Python解析XML中的特殊字元和轉義序列 Aug 08, 2023 pm 12:46 PM

Python解析XML中的特殊字元和轉義序列XML(eXtensibleMarkupLanguage)是一種常用的資料交換格式,用於在不同系統之間傳輸和儲存資料。在處理XML檔案時,經常會遇到包含特殊字元和轉義序列的情況,這可能會導致解析錯誤或誤解資料。因此,在使用Python解析XML檔案時,我們需要了解如何處理這些特殊字元和轉義序列。一、特殊字元和

See all articles