我正在使用linq代码解析XML文件。这是我的代码。我想要绑定详细信息和图像列表。
var query = from l in xmlDoc.Descendants("Person")
from detail in l.Descendants("Details")
select new Notch
{
name = (string)l.Attribute("name").Value,
detail= l.Element("detail").Select(a => (string)a.Attribute("detailName")).ToList(),
Image = l.Element("detail").Elements("event_image").Select(x => (string)x.Attribute("url")).ToString()
};
foreach (var result in query)
{
foreach (var detail in result.detail)
{
Console.WriteLine(detail);
}
}
我尝试了这段代码,但我得到了如下输出..但我希望详细信息和图片列表。
Raja
System.Collection.Generic.List'1[string.system]
Rama
System.Collection.Generic.List'1[string.system]
答案 0 :(得分:0)
问题是你得到的是一个字符串列表,而不是一个唯一的字符串。 尝试使用此代码,以便使用新行连接每个字符串并能够正确打印它:
detail = string.Join(System.Environment.NewLine, l.Element("detail").Select(a => (string)a.Attribute("detailName")))
完整代码:
var query = from l in xmlDoc.Descendants("Person")
from detail in l.Descendants("Details")
select new Notch
{
name = (string)l.Attribute("name").Value,
detail= string.Join(System.Environment.NewLine, l.Element("detail").Select(a => (string)a.Attribute("detailName"))),
Image = l.Element("detail").Elements("event_image").Select(x => (string)x.Attribute("url")).ToString()
};
foreach (var result in query)
{
foreach (var detail in result.detail)
{
Console.WriteLine(detail);
}
}