如何使用Linq to XML检索数据?

时间:2009-04-21 22:10:21

标签: .net linq-to-xml

我需要从以下XML片段中找到ShippingMethod和属性CodeDestination

<ScoreRule>
    <ShippingMethod Code="UPS1DA">
        <Destination Country="US" Area="IL" Value="0" />
    </ShippingMethod>
</ScoreRule>

如何使用Linq to XML检索该数据?

2 个答案:

答案 0 :(得分:3)

这是你想要的吗?

XElement scoreRuleElement = XElement.Parse("<ScoreRule><ShippingMethod Code=\"UPS1DA\"><Destination Country=\"US\" Area=\"IL\" Value=\"0\" /></ShippingMethod></ScoreRule>");

XElement shippingMethodElement = scoreRuleElement.Element("ShippingMethod");
string code = shippingMethodElement.Attribute("Code").Value;
XElement destinationElement = shippingMethodElement.Element("Destination");

答案 1 :(得分:2)

以下是XML查询表达式的链接以选择它。

我不知道您是如何加载初始数据的,所以我只是将其解析为文档,但您应该根据获取数据的方式创建XDocument。

var data = XDocument.Parse("<ScoreRule><ShippingMethod Code=\"UPS1DA\"><Destination Country=\"US\" Area=\"IL\" Value=\"0\" /></ShippingMethod></ScoreRule>");

            var results = from item in data.Descendants("ShippingMethod")
                          select new
                              {
                                  ShippingMethodCode = item.Attribute("Code").Value,
                                  Country = item.Element("Destination").Attribute("Country").Value,
                                  Area = item.Element("Destination").Attribute("Area").Value
                              };
相关问题