XML获取同名的下一个节点

XML获取同名的下一个节点

本文介绍了Linq to XML获取同名的下一个节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的XML

<assets>
    <asset>
        <metadata Id="ItemType" Value="Image"/>
        <metadata Id="ItemUri" Value="http://blah.png"/>
    </asset>
    <asset>
        <metadata Id="ItemType" Value="Image"/>
        <metadata Id="ItemUri" Value="http://blah2.png"/>
    </asset>
</assets>

如何获取包含URI的第二个<metadata>值?

How do I get the 2nd <metadata>'s value containing the URI?

List<Asset> assets = (from asset in xmlDocument.Descendants("asset")
                              select new Asset
                              {
                                  ItemType = asset.Element("metadata").Attribute("Value").Value,
                                  ItemUri = asset.Element("metadata").Attribute("Value").Value
                              }).ToList<Asset>();

当前,我的代码当然从第一个<metadata>返回相同的值.

Currently my code just returns the same value from the first <metadata> of course.

推荐答案

这就是我最终要做的.上面的答案很好,但是如果<metadata>的顺序不正确,那么我会得到错误的数据.这样,无论查询顺序如何,我都可以查询并得到正确的查询.

This is what I ended up doing. The answers above where good but if the <metadata>s are not in order then I'll get the wrong data. This way I do a query and get the correct one no matter the order.

List<Asset> assets = (from asset in xmlDocument.Descendants("asset")
                              select new Asset
                              {
                                  ItemType = asset.Elements().Single(x => x.Attribute("Id").Value == "ItemType").Attribute("Value").Value,
                                  ItemUri = asset.Elements().Single(x => x.Attribute("Id").Value == "ItemUri").Attribute("Value").Value,
                              }).ToList<Asset>();

这篇关于Linq to XML获取同名的下一个节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 09:12