2009-04-21 74 views
1

我需要找到下面这段XML的ShippingMethod和属性CodeDestination如何检索Linq to XML数据?

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

如何检索使用LINQ到XML数据?

+0

你只是在寻找语法?你有关于实施的具体问题吗?你有没有一种语言你想看到实施?你不知道从哪里开始? – 2009-04-21 22:28:22

回答

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 
           }; 
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"); 
+0

除非您确定属性“代码”将始终在两个步骤中获取该值。 string code = string.Empty; XAttribute codeAttribute = shippingMethodElement.Attribute(“Code”); (codeAttribute!= null) code = codeAttribute.Value; } – Erin 2009-04-21 22:45:26