0

次の URL から xml ファイルを解析したい:" http://restservice.com/RestServiceImpl.svc/ghhf/cvr "

次のコードを使用して XDocument を取得できます。

private void Search(object sender, RoutedEventArgs e)
{
    string url = "http://restservice.schoolpundit.com/RestServiceImpl.svc/search_name/cvr";
    WebClient twitter = new WebClient();
    twitter.DownloadStringCompleted += new DownloadStringCompletedEventHandler(twitter_DownloadStringCompleted);
    twitter.DownloadStringAsync(new Uri(url));
}

void twitter_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    if (e.Error != null)
        return;
    XDocument doc = XDocument .Parse(e.Result);

    var list = from child in  doc.Descendants("Institutions_search_name")
               select new listrows {
                  inst_name=doc.Element("Inst_name").Value;
               };

     Listbox.ItemSource=list;
} 

しかし、それは Inst_name を表示していません。実際には、doc.Descendants("Institutions_search_name") に入っていません。例外も表示されていません。

4

1 に答える 1

7

名前空間が欠落しているだけだと思いますが、doc.Element代わりにchild.Element. XML を見ると、ルート要素に次のように表示されます。

 xmlns="http://schemas.datacontract.org/2004/07/RestService"

これは、名前空間が明示的に指定されていないすべての要素がその名前空間にあることを意味します。

幸いなことに、LINQ to XML を使用すると、これを非常に簡単に処理できます。

XNamespace ns = "http://schemas.datacontract.org/2004/07/RestService";
var list = from child in doc.Descendants(ns + "Institutions_search_name")
           select new listrows {
               inst_name=child.Element(ns + "Inst_name").Value
           };

おそらくクエリ式なしでそれを行うでしょうが:

XNamespace ns = "http://schemas.datacontract.org/2004/07/RestService";
var list = doc.Descendants(ns + "Institutions_search_name")
              .Select(x => new listrows { 
                         inst_name = child.Element(ns + "Inst_name").Value
                      });

実際、単一の文字列を選択しているだけlistrowsなので、ビットを取り除きます。

XNamespace ns = "http://schemas.datacontract.org/2004/07/RestService";
var list = doc.Descendants(ns + "Institutions_search_name")
              .Select(x => child.Element(ns + "Inst_name").Value);

また、 と の両方が .NET の命名規則listrowsinst_name違反していることにも注意してください。すべての人がコードを読みやすくするために、これらの規則と一致するように努めることは価値があります。

于 2013-05-08T06:02:42.257 に答える