如何針對空的查詢結果集進行偵錯 (LINQ to XML)

查詢 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");
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")

此範例會產生以下結果:

Result set follows:
End of result set

範例:命名空間中 XML 的查詢正確

此範例顯示在命名空間中建立的 XML,以及正確撰寫的查詢程式碼。

解決方案是要宣告與初始化 XNamespace 物件,並在指定 XName 物件時使用。 在這個情況下,Elements 方法的引數為 XName 物件。

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(CInt(el))
        Next
        Console.WriteLine("End of result set")
    End Sub
End Module

此範例會產生以下結果:

Result set follows:
1
2
3
End of result set

另請參閱