XML ツリーのクエリにおける最も一般的な問題の 1 つは、XML ツリーに既定の名前空間がある場合に、XML が名前空間に含まれていないものとして開発者がクエリを記述してしまうことです。
このトピックの最初に示す一連の例では、既定の名前空間内の XML が読み込まれ、クエリが不適切に実行される典型的な例を示しています。
2 番目に示す一連の例では、名前空間内の XML に対してクエリを実行できるようにするために必要な修正を示しています。
詳細については、「XML 名前空間の使用」を参照してください。
使用例
この例では、名前空間内にある XML の作成、および空の結果セットを返すクエリを示します。
XElement root = XElement.Parse(
@"<Root xmlns='https://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='https://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 の作成と、適切に記述されたクエリを示します。
C# を使用する場合は、XNamespace オブジェクトを宣言して初期化し、そのオブジェクトを XName オブジェクトの指定時に使用することで問題を解決できます。 この場合、Elements メソッドの引数は XName オブジェクトです。
Visual Basic の場合は、グローバルな既定の名前空間を宣言して初期化することで問題を解決できます。 これにより、すべての XML プロパティが既定の名前空間に配置されます。 この例を正しく動作させるために必要な変更はこれだけです。
XElement root = XElement.Parse(
@"<Root xmlns='https://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 = "https://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="https://www.adventure-works.com">
Module Module1
Sub Main()
Dim root As XElement = _
<Root xmlns='https://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