如何控制命名空間前置詞 (LINQ to XML)

本文說明如何在透過 C# 和 Visual Basic 序列化 XML 樹狀結構時,控制命名空間前置詞。

在許多情況下,沒有必要控制命名空間前置詞。 不過有某些 XML 程式設計工具需要這麼做。 例如,您所操作的 XSLT 樣式表或 XAML 文件中,可能包含參考特定命名空間前置詞的內嵌 XPath 運算式。 在此情況下,請務必使用這些前置詞來序列化文件。 這是控制命名空間前置詞的常見原因。

另一個常見原因是,您要讓使用者手動編輯 XML 文件,而且您要建立使用者便於輸入的命名空間前置詞。 例如,您可能要產生 XSD 文件。 若要轉換結構描述,建議您使用 xsxsd 做為結構描述命名空間的前置詞。

若要控制命名空間前置詞,您可插入宣告命名空間的屬性。 如果宣告具有特定前置詞的命名空間,LINQ to XML 會在序列化時嘗試允許命名空間前置詞。

若要建立宣告具有特定前置詞之命名空間的屬性,您可以建立屬性,其中之屬性名稱的命名空間為 Xmlns,而屬性的名稱為命名空間前置詞。 屬性的值為命名空間的 URI。

範例:建立兩個具有前置詞的命名空間

這個範例會宣告兩個命名空間。 它會為 http://www.adventure-works.com 命名空間指定 aw 前置詞,www.fourthcoffee.com 命名空間則是 fc 前置詞。

XNamespace aw = "http://www.adventure-works.com";
XNamespace fc = "www.fourthcoffee.com";
XElement root = new XElement(aw + "Root",
    new XAttribute(XNamespace.Xmlns + "aw", "http://www.adventure-works.com"),
    new XAttribute(XNamespace.Xmlns + "fc", "www.fourthcoffee.com"),
    new XElement(fc + "Child",
        new XElement(aw + "DifferentChild", "other content")
    ),
    new XElement(aw + "Child2", "c2 content"),
    new XElement(fc + "Child3", "c3 content")
);
Console.WriteLine(root);
Imports <xmlns:aw="http://www.adventure-works.com">
Imports <xmlns:fc="www.fourthcoffee.com">

Module Module1

    Sub Main()
        Dim root As XElement = _
            <aw:Root>
                <fc:Child>
                    <aw:DifferentChild>other content</aw:DifferentChild>
                </fc:Child>
                <aw:Child2>c2 content</aw:Child2>
                <fc:Child3>c3 content</fc:Child3>
            </aw:Root>
        Console.WriteLine(root)
    End Sub

This example produces the following output:

```xml
<aw:Root xmlns:aw="http://www.adventure-works.com" xmlns:fc="www.fourthcoffee.com">
  <fc:Child>
    <aw:DifferentChild>other content</aw:DifferentChild>
  </fc:Child>
  <aw:Child2>c2 content</aw:Child2>
  <fc:Child3>c3 content</fc:Child3>
</aw:Root>

另請參閱