質問

Silverlight DataGridをWCFサービス呼び出しの結果にバインドしようとしています。グリッドにデータが表示されていなかったため、デバッガーを実行すると、XDocument.Descendants()が有効な要素名を渡しても要素を返さなかったことがわかります。サービスから返されるXMLは次のとおりです。

<ArrayOfEmployee xmlns="http://schemas.datacontract.org/2004/07/Employees.Entities" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <Employee>
    <BirthDate>1953-09-02T00:00:00</BirthDate>
    <EmployeeNumber>10001</EmployeeNumber>
    <FirstName>Georgi</FirstName>
    <Gender>M</Gender>
    <HireDate>1986-06-26T00:00:00</HireDate>
    <LastName>Facello</LastName>
  </Employee>
  <Employee>
    <BirthDate>1964-06-02T00:00:00</BirthDate>
    <EmployeeNumber>10002</EmployeeNumber>
    <FirstName>Bezalel</FirstName>
    <Gender>F</Gender>
    <HireDate>1985-11-21T00:00:00</HireDate>
    <LastName>Simmel</LastName>
  </Employee>
</ArrayOfEmployee>

そして、Linq to XMlを使用して匿名オブジェクトのコレクションに結果をロードし、コレクションをグリッドにバインドするために使用する方法を次に示します。

void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs args)
{
    if (args.Error != null) return;
    var xml = XDocument.Parse(args.Result);
    var employees = from e in xml.Descendants("Employee")
                    select new
                    {
                        EmployeeNumber = e.Element("EmployeeNumber").Value,
                        FirstName = e.Element("FirstName").Value,
                        LastName = e.Element("LastName").Value,
                        Birthday = e.Element("BirthDate").Value
                    };
    DataGrid.SelectedIndex = -1;
    DataGrid.ItemsSource = employees;
}

xml.Descendants(&quot; Employee&quot;)が何も返さない理由は何ですか?

ありがとう!

役に立ちましたか?

解決

Descendentsに渡される文字列パラメーターは、実際には暗黙的にXNameオブジェクトに変換されます。 XNameは完全修飾要素名を表します。

ドキュメントはネームスペース「i」を定義しているため、Employeeにアクセスするには完全修飾名を使用する必要があると思います。すなわち。 i:Employee。プレフィックス&quot; i:は、実際には完全なネームスペース文字列に解決されます。

次のようなことを試しましたか:

XName qualifiedName = XName.Get("Employee", "http://www.w3.org/2001/XMLSchema-instance");

var employees = from e in xml.Descendants(qualifiedName)

...

他のヒント

親要素の名前空間は含まれていません:

XNameSpace ns = "http://schemas.datacontract.org/2004/07/Employees.Entities";
foreach (XElement element in xdoc.Descendants(ns + "Employee")
{
    ...
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top