我想阅读下面的XML并按以下顺序打印输出。你能帮忙查询如何绑定图像吗?
<?xml version="1.0" encoding="utf-8"?>
<Book>
<L1 id="100">
<Subjects>
<subject>
<thumb_image>
<image url= url="http://dev2.merceed.jpeg1"/>
<thumb_image>
</subject>
<subject>
<thumb_image>
<image url= url="http://dev2.merceed.jpeg2"/>
<thumb_image>
</subject>
<subject>
<thumb_image>
<image url= url="http://dev2.merceed.jpeg3"/>
<thumb_image>
</subject>
</Subjects>
</L1>
<L2 id="200">
<Subjects>
<subject>
<thumb_image>
<image url= url="http://dev2.merceed.jpeg"/1>
<thumb_image>
</subject>
<subject>
<thumb_image>
<image url= url="http://dev2.merceed.jpeg2"/>
<thumb_image>
</subject>
<subject>
<thumb_image>
<image url= url="http://dev2.merceed.jpeg2"/>
<thumb_image>
</subject>
</Subjects>
</L2>
<Book>
我想输出
100
IMAGE1
图像2
的Image3
.............
200
图像11
Image12
Image13
我正在使用我的代码
var query = from l in xmlDoc.Descendants("L1")
from subject in l.Descendants("Subjects")
select new Notch
{
name = (string)l.Attribute("id").Value,
SubjectName= l.subject("article").Select(a => (string)a.Attribute("SubjectName")).ToList(),
url = l.Element("article").Elements("thumb_image").Select(x => (string)x.Attribute("url")).ToString()
};
foreach (var result in query)
{
foreach (var titles in result.SubjectName)
{
Console.WriteLine(titles);
}
foreach (var image in category.Image)
{
Console.WriteLine(image);
}
}
答案 0 :(得分:0)
根本不清楚您希望当前查询如何工作(例如l.subject
,以及使用article
并不会出现在您的XML中)但我怀疑你想要的东西:
var query = from l in xmlDoc.Descendants("Li")
select new Notch
{
name = (string) l.Attribute("id"),
SubjectName = l.Element("Subjects")
.Elements("subject")
.Select(x => (string) x.Attribute("SubjectName"))
.ToList()
};
我强烈建议您仔细查看您的变量和属性名称。对于名为SubjectName
的属性来说,拥有集合值是没有意义的,对于名为titles
的迭代变量来说,它没有意义。表示单个值。注意这类事情可以更容易地维护代码。
答案 1 :(得分:0)
var query =
from l in xmlDoc.Root.Elements()
select new {
Id = (int)l.Attribute("id"),
Subjects = l.Element("Subjects")
.Elements("subject")
.Select(s => (string)s.Attribute("SubjectName"))
.ToList()
};
foreach (var item in query)
{
Console.WriteLine(item.Id);
foreach (var name in item.Subjects)
Console.WriteLine(name);
}
更新:编辑完问题后(您已将Li元素更改为L1和L2元素),您应使用xmlDoc.Root.Elements()
代替xmlDoc.Root.Elements("Li")