1

也许这个标题令人困惑。

使用 linq 读取 xml 时遇到一个非常奇怪的问题。

我的 XML 是这样的:

<Result>
  <Hotels>    
    <Hotel>
      <Documents>
        <Image>
          <Url>http://www.someUrlToImage1</Url>
        </Image>
        <Image>
          <Url>http://www.someUrlToImage2</Url>
        </Image>
      </Documents>
      <Room>
        <Documents>
          <Image>
            <Url>http://www.someUrlToImage3</Url>
          </Image>
          <Image>
            <Url>http://www.someUrlToImage4</Url>
          </Image>
        </Documents>
       </Room>
    </Hotel>
  <Hotels>
<Result>

如果我想获得关于酒店的两张图片,我会获得所有 4 张图片...:

Hotel temp = (from x in  doc.Descendants("Result").Descendants("Hotels").Descendants("Hotel")
             select new Hotel()

             HotelImages= new Collection<string>(
             x.Descendants("Documents").SelectMany(
               documents => documents.Descendants("Images").Select(
                document => (string)document.Descendants("URL").FirstOrDefault() ?? "")).ToList())

             }).First();

我希望有人在我之前遇到过这个问题。

4

2 回答 2

4

Descendants返回父元素内任意位置的所有匹配元素,而不仅仅是其下方的那些。x有两个后代Documents标签,您将从它们中获取图像。

尝试使用Elements而不是Descendants.

于 2013-03-15T15:36:42.727 回答
1

Descendants()选择当前节点的后代,而不仅仅是直接子节点,因此x.Descendants("Documents")选择两个Documents节点,而不仅仅是第一个。

这怎么样:

Hotel temp = (from x in  doc.Descendants("Hotel")
              select new Hotel()
              {
                HotelImages = new Collection<string>(
                                  x.Elements("Documents")
                                   .Descendants("Images")
                                   .Where(i => (string)i.Attribute("Class") == "jpg")
                                   .Select(img => (string)img.Element("URL") ?? "")
                                   .ToList()
                              )
              }).First();
于 2013-03-15T15:39:01.183 回答