XML 樹中表示的默認命名空間不在查詢範圍內。如果您的 XML 在默認命名空間內,仍須聲明一個XNamespace 變量,並將該變量與本地名稱組合在一起,生成一個限定名,在查詢中使用。
查詢 XML 樹時遇到的一個最常見問題是,如果 XML 樹具有默認命名空間,開發人員在編寫查詢時,有時會將 XML 視爲不在命名空間內。
本主題的第一個示例集演示一種加載但是按不正確方式查詢默認命名空間中的 XML 的典型方式。
第二個示例集演示必需的更正,以便可以查詢命名空間中的 XML。
有關更多信息,請參見 使用 XML 命名空間。
此示例演示如何在命名空間中創建 XML 和一個返回空結果集的查詢。
代碼
XElement root = XElement.Parse( @"<Root xmlns='http://www.adventure-works.com'> <Child>1</Child> <Child>2</Child> <Child>3</Child> <AnotherChild>4</AnotherChild> <AnotherChild>5</AnotherChild> <AnotherChild>6</AnotherChild> </Root>"); IEnumerable<XElement> c1 = from el in root.Elements("Child") select el; Console.WriteLine("Result set follows:"); foreach (XElement el in c1) Console.WriteLine((int)el); Console.WriteLine("End of result set");
Module Module1 Sub Main() Dim root As XElement = _ <Root xmlns='http://www.adventure-works.com'> <Child>1</Child> <Child>2</Child> <Child>3</Child> <AnotherChild>4</AnotherChild> <AnotherChild>5</AnotherChild> <AnotherChild>6</AnotherChild> </Root> Dim c1 As IEnumerable(Of XElement) = _ From el In root.<Child> _ Select el Console.WriteLine("Result set follows:") For Each el As XElement In c1 Console.WriteLine(CInt(el)) Next Console.WriteLine("End of result set") End Sub End Module
註釋
此示例產生下面的結果:
Result set follows: End of result set
本示例演示如何在命名空間中創建 XML 和一個正確編碼的查詢。
與上述不正確編碼的示例相比,使用 C# 時的正確方法是聲明和初始化一個 XNamespace 對象,並在指定XName 對象時使用它。在這種情況下,Elements 方法的參數是一個 XName 對象。
而在使用 Visual Basic 時,正確的方法是聲明和初始化一個全局默認命名空間。這樣會將所有 XML 屬性放入該默認命名空間。無需對該示例做任何其他修改,即可使它正常運行。
代碼
XElement root = XElement.Parse( @"<Root xmlns='http://www.adventure-works.com'> <Child>1</Child> <Child>2</Child> <Child>3</Child> <AnotherChild>4</AnotherChild> <AnotherChild>5</AnotherChild> <AnotherChild>6</AnotherChild> </Root>"); XNamespace aw = "http://www.adventure-works.com"; IEnumerable<XElement> c1 = from el in root.Elements(aw + "Child") select el; Console.WriteLine("Result set follows:"); foreach (XElement el in c1) Console.WriteLine((int)el); Console.WriteLine("End of result set");
Imports <xmlns="http://www.adventure-works.com"> Module Module1 Sub Main() Dim root As XElement = _ <Root xmlns='http://www.adventure-works.com'> <Child>1</Child> <Child>2</Child> <Child>3</Child> <AnotherChild>4</AnotherChild> <AnotherChild>5</AnotherChild> <AnotherChild>6</AnotherChild> </Root> Dim c1 As IEnumerable(Of XElement) = _ From el In root.<Child> _ Select el Console.WriteLine("Result set follows:") For Each el As XElement In c1 Console.WriteLine(el.Value) Next Console.WriteLine("End of result set") End Sub End Module
註釋
此示例產生下面的結果:
Result set follows: 1 2 3 End of result set