views:

52

answers:

2

I have a very simple XML:

<Rows>
  <Row>
    <id>1</id>
    <name>foo</name>
    <more>xyz</more>
  </Row>
  <Row>
    <id>2</id>
    <name>bar</name>
    <more>abc</more>
  </Row>
</Rows>

and need to do lots of querying on the ID, speed being really key.

Would it be more efficient loading the XML into a datatable and creating a PK on id and doing the querying on the data table?
or
Is this the most efficient Linq/Xml code?

myRows = XDocument.Parse(xmlString);               
result = myRows.Element("Rows").Elements("Row").Single(r => r.Element("id").Value == "1");
if (result != null)
    string name = result.Element("name").Value;

Edited For clarity: There are more elements than id & name.

+2  A: 

Load it into a Dictionary<int, string>, assuming the id field is unique and an int:

var myRows = XDocument.Parse(xmlString);
var myDictionaryOfRows = myRows
    .Descendants("Row")
    .ToDictionary(e => int.Parse(e.Element("id").Value), 
        e => e.Element("name").Value);
Console.WriteLine(myDictionaryOfRows[1]);
Yuriy Faktorovich
Andrew White
@Andrew could you deserialize to a `Dictionary<int, youTypeWithAttributes>`?
Yuriy Faktorovich
A: 

I would recommend deserializing the xml into a class. So you'd end up with a collection of custom type objects. Then use your linq on that collection.

But I prefer working with a class than raw xml :)

The xsd tool comes in handy for generating your class from a schema (though sometimes you need to refine the schema so that you don't end up with crazy multidimensional arrays (crazy if you don't require them).

I wouldn't have thought using a database would give better speed than just dealing with this in memory.

Jen