C# 用C语言解析复杂XML#
我正在尝试用C#解析一个复杂的XML,我正在使用Linq。基本上,我向服务器发出请求,得到XML,代码如下:C# 用C语言解析复杂XML#,c#,xml,windows-phone-7,C#,Xml,Windows Phone 7,我正在尝试用C#解析一个复杂的XML,我正在使用Linq。基本上,我向服务器发出请求,得到XML,代码如下: XElement xdoc = XElement.Parse(e.Result); this.newsList.ItemsSource = from item in xdoc.Descendants("item") select new ArticlesItem { //Image = item.Element("image").Element("url").Val
XElement xdoc = XElement.Parse(e.Result);
this.newsList.ItemsSource =
from item in xdoc.Descendants("item")
select new ArticlesItem
{
//Image = item.Element("image").Element("url").Value,
Title = item.Element("title").Value,
Description = this.Strip(item.Element("description").Value).Substring(0, 200).ToString()
}
这是XML结构:
<item>
<test:link_id>1282570</test:link_id>
<test:user>SLAYERTANIC</test:user>
<title>aaa</title>
<description>aaa</description>
</item>
1282570
斯莱耶塔尼奇
aaa
aaa
如何访问属性测试:例如link_id
谢谢 当前您的XML无效,因为未声明
测试
命名空间,您可以这样声明它:
<item xmlns:test="http://foo.bar">
<test:link_id>1282570</test:link_id>
<test:user>SLAYERTANIC</test:user>
<title>aaa</title>
<description>aaa</description>
</item>
在XML中编写查询的步骤
命名空间,则必须使用XName对象
具有正确命名空间的。对于
C#,最常见的方法是
使用
包含URI的字符串,然后使用
加法运算符重载到
将名称空间与本地
名字
要检索link_id元素的值,您需要为test:link元素声明并使用
因为您没有在示例XML中显示名称空间声明,所以我假设它是在XML文档中的某个地方声明的。您需要在XML中找到名称空间声明(类似于xmlns:test=”http://schema.example.org),通常在XML文档的根中声明
了解这一点后,可以执行以下操作来检索link_id元素的值:
XElement xdoc = XElement.Parse(e.Result);
XNamespace testNamespace = "http://schema.example.org";
this.newsList.ItemsSource = from item in xdoc.Descendants("item")
select new ArticlesItem
{
Title = item.Element("title").Value,
Link = item.Element(testNamespace + "link_id").Value,
Description = this.Strip(item.Element("description").Value).Substring(0, 200).ToString()
}
有关更多信息,请参阅和和。看起来“test”是一个名称空间?如果是这样,XName对象应该可以帮助您@伊万,因为那样不行。
XElement xdoc = XElement.Parse(e.Result);
XNamespace testNamespace = "http://schema.example.org";
this.newsList.ItemsSource = from item in xdoc.Descendants("item")
select new ArticlesItem
{
Title = item.Element("title").Value,
Link = item.Element(testNamespace + "link_id").Value,
Description = this.Strip(item.Element("description").Value).Substring(0, 200).ToString()
}