0

我正在使用 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]
4

1 回答 1

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);
     }  
 }
于 2013-02-28T10:28:46.390 回答