1

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?

Gavin Miller
  • 43,168
  • 21
  • 122
  • 188
Sreedhar
  • 29,307
  • 34
  • 118
  • 188
  • Are you just looking for syntax? Did you have a specific question about implementation? Did you have a language you wanted to see the implementation in? Do you not know where to start? – Dan Esparza Apr 21 '09 at 22:28

2 Answers2

3

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
  • 19,610
  • 14
  • 75
  • 137
  • 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 Apr 21 '09 at 22:45
2

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
  • 4,229
  • 2
  • 23
  • 25