views:

165

answers:

2

I need to find ShippingMethod and the attribute Code and Destination from the following piece of XML:

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

How do I retrieve that data with Linq to XML?

+3  A: 

Is this what you want?

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");
dommer
Unless you are sure that the Attribute "Code" will always be there get the value in 2 steps.string code = string.Empty;XAttribute codeAttribute = shippingMethodElement.Attribute("Code");if(codeAttribute != null){ code = codeAttribute.Value;}
Erin
+2  A: 

Here is the link to XML query expression to select it.

I didn't know how you were loading your initial data, so I just parsed it in to a document, but you should create your XDocument according to how you are getting your data.

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
                              };
Brian ONeil