嗨,如何用后代C#中的后代解析xml

时间:2012-07-15 23:42:42

标签: c# xml parsing linq-to-xml descendant

我正在尝试解析这个xml并且可以成功获取名称和描述,但是将图像放在一起很棘手。两个单独的代码解析都有效,但我想做一个解析,所以我可以将它们全部绑定到一个列表框。

xml看起来像这样

<stickers>
    <sticker>
        <imageData>
            <baseImageUrl> ... want this  </baseImageUrl>
            <sizes>
                <size>  don't care about this </size>
            </size>
            <imageUrlSuffix> ..want this </imageUrlSuffix>
        </imageData>
        <description>.... want this </description>
        <name>  --want this </name>
    <sticker>
<stickers>

我的代码适用于两者但分开。我如何将其组合成一个解析...

XDocument streamFeed = XDocument.Load(new StringReader(response.Content));
var imagedata = from query in streamFeed.Descendants("sticker").Elements("imageData")
    select new Stickers
    {
        image = (string)query.Element("baseImageUrl") + "huge" + (string)query.Element("imageUrlSuffix"),
    };


var data = from query in streamFeed.Descendants("sticker")
    select new Stickers
    {
        name = (string)query.Element("name"),
        description = (string)query.Element("description"),   
    };

stickersListBox.ItemsSource = imagedata.Union(data);

数据显示在列表框中,但标签上方有贴纸,而不是并排。

由于


感谢下面的Thomas,下面的代码可以正常工作,但是有些用户配置文件会出现Null Referenced Exception(包括我自己的配置文件显然有数据)感谢Thoamas的帮助,或许这是一个无关的bug?

XDocument streamFeed = XDocument.Load(new StringReader(response.Content));

                    var query =
                        from sticker in streamFeed.Root.Descendants("sticker")
                        let imageData = sticker.Element("imageData")
                        select new Stickers
                        {
                            name = (string)sticker.Element("name"),
                            description = (string)sticker.Element("description"),
                            image = (string)imageData.Element("baseImageUrl") + "huge" + (string)imageData.Element("imageUrlSuffix")
                        };

                    stickersListBox.ItemsSource = query;

1 个答案:

答案 0 :(得分:0)

如果我正确理解了这个问题,这应该做你想做的事情:

XDocument streamFeed = XDocument.Load(new StringReader(response.Content));
var query =
    from sticker in streamFeed.Root.Elements("sticker")
    let imageData = sticker.Element("imageData")
    select new Stickers
    {
        name = (string)sticker.Element("name"),
        description = (string)sticker.Element("description"),   
        image = (string)imageData.Element("baseImageUrl") + "huge" + (string)imageData.Element("imageUrlSuffix")
    };

stickersListBox.ItemsSource = query;