开发者

Using LINQ to XML to get a specific record

We store static data in an XML file with different groupings of data. The file is actually quite large and I've pared it down for this question. Each of these are a small subset of their data.

<?xml version="1.0" encoding="utf-8" ?>
<datasets>
    <dataset id="USRegions">
        <record code="SoCal">Southern California</record>
        <record code="NoCal">Northen California</record>
    </dataset>
    <dataset id="Countries">
        <record code="US" callingcode="1|US">United States</record>
        <record code="CA" callingcode="1|CA">Canada</record>
        <record code="GB" callingcode="44|GB">United Kingdom</record>
        <record code="MX" callingcode="52|MX">Mexico</record>
    </dataset>
</datasets>

For purposes of validation I want to make sure that the passed in country code, "US" for example, exists in the static data. I can开发者_如何学Python get to the recordset with this query, but I'm stumped on how to drill deeper into the data.

var dataset = from record in _xAddressData.Descendants("dataset")
          where (string) record.Attribute("id") == "Countries"
          select record.DescendantNodes();


Try this

var dataset = from dataset in _xAddressData.Descendants("dataset")
          let codes = dataset.Descendants("record").Select(r => r.Attribute("code").Value)
          where (string) dataset.Attribute("id") == "Countries" &&
          codes.All(c => MyListOfCountryCodes.Contains(c))
          select record.DescendantNodes();


One approach:

static bool HasCountry(this XDocument document, string country)
{
    return document.Root.Elements("dataset")
                        .Any(d => (string)d.Attribute("id") == "Countries"
                          && d.Elements("record")
                              .Any(r => (string)r.Attribute("code") == country));
}

Used like:

var hasUS = _xAddressData.HasCountry("US");


I'll answer in the form of using the extension methods (I just think they're a lot tidier)

var findKey = "US";
var rows = doc.Descendants("dataset")
    .Single(x=> x.Attribute("id").Value == "Countries")
    .Elements()
    .Where(x => x.Attribute("code").Value == findKey);

Of course, if all you're looking to do is have a boolean value to say if the element exists or not, just replace the Where with Any:

var keyExists = doc.Descendants("dataset")
    .Single(x=> x.Attribute("id").Value == "Countries")
    .Elements()
    .Any(x => x.Attribute("code").Value == findKey);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜