tags:

views:

114

answers:

1

I'm writing a program to parse some third-party XML files. The structure is something like...

<CharacterSheet>
 ...
 <StatBlock>
  ...
  <Stat>
   ...
   <alias />
   ...
  </Stat>
  ...
 </StatBlock>
 ...
</CharacterSheet>

I'm using this in to get some practice with linq, and I'm fining I have to write some really ugly chained queries to get what I want, a list of stats and all their alias.

var CharSheet = from i in character.Elements()
  where i.Name == "CharacterSheet"
  select i;

var StatBlocks = from sheet in CharSheet
   from statBlock in sheet.Elements()
   where statBlock.Name == "StatBlock"
   select statBlock;

var stats = from statBlock in StatBlocks
     from stat in statBlock.Elements()
     select stat;

var statAliases = from stat in stats
    from alias in stat.Elements()
    where alias.Name == "alias"
    select new { stat, alias };

And I realize I could make that into one really long query using "into" (which is originally how I had it), but that just made it even more dense and difficult to work with.

It seems like there's got to be a simpler way to do what I'm trying to do.

+6  A: 

You could use XPathSelectElements() (which might be a better idea, to be honest), or you could use the Elements() extension method:

var query = character.Elements("CharacterSheet")
                     .Elements("StatsBlock")
                     .Elements()
                     .Elements("alias")
                     .Select(x => new { stat=x.Parent, alias=x};
Jon Skeet
Thanks! That was actually my natural inclination (trying .Elements("name"), but in visual studio it was saying that the only argument I could pass was an XName, so I didn't even try to use a string and I couldn't figure out how to make an XName.But yeah, that works perfectly (or, at least, the compiler doesn't mind me putting strings there... I haven't tested it yet, but I suspect it should be fine).Thanks!
Asmor
Yup, you're using the implicit conversion from string to XName, which is used almost universally :)
Jon Skeet
The XName thing is a bit of a pain as the "intellisense" isn't intelligent enough to point developers that strings are implicitly converted.
Peter