mad*_*n V 0 c# linq xml-parsing windows-phone-8
我想从以下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;
}
Run Code Online (Sandbox Code Playgroud)
但它没有显示任何Inst_name,实际上它没有进入doc.Descendants("institutions_search_name")它也没有显示任何异常.如果我做了任何错误纠正我.
我认为你只是错过了命名空间 - 尽管你也在调用doc.Element而不是child.Element.如果你看一下XML,你会在root元素中看到这个:
xmlns="http://schemas.datacontract.org/2004/07/RestService"
Run Code Online (Sandbox Code Playgroud)
这意味着没有明确指定名称空间的每个元素都在该名称空间中.
幸运的是,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
};
Run Code Online (Sandbox Code Playgroud)
虽然我可能在没有查询表达式的情况下这样做:
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
});
Run Code Online (Sandbox Code Playgroud)
事实上,鉴于你只是选择一个字符串,我会摆脱这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);
Run Code Online (Sandbox Code Playgroud)
还要注意,listrows并inst_name违反.NET命名约定-这是值得尝试与这些公约相一致,使您的代码更容易给大家看了.
| 归档时间: |
|
| 查看次数: |
3872 次 |
| 最近记录: |