Most efficient use of LINQ to XML
I'm using LINQ to XML to parse an XML document. I also have the ability to influence the design of the XML schema. A given XML element, Person, may have one or more Address elements as children. Would it be more efficient when parsing to have the XML defined so that Person contains one or more Address nodes or would it be better for Person to contain an Addresses node that in turn contained one or more A开发者_如何转开发ddress nodes? Thanks.
The fewer elements between you and the desired data, the better. But the point of using the structure of XML is to make sense of the data. One question to ask is: will it be necessary to group addresses together under each person? If so, then it pays to have an intermediate element to describe what the grouping is, eg:
<Person>
<Addresses Group="Summer">
<Address Street="123 Street Name" .../>
</Addresses>
<Addresses Group="Winter">
<Address Street="456 Other Street" .../>
</Addresses>
</Person>
If no, then there's no point in having the intermediate element, and it will cost you the overhead of storing and parsing it.
If you're worried about how easy it will be to get collections of child elements in your code, LINQ-to-XML makes it easy to deal with either scenario. For example:
<Person>
<Address .../>
<Address .../>
<Phone .../>
<Phone .../>
<Email .../>
</Person>
You can extract what you want trivially:
var Addresses = personElement.Elements("Address");
var PhoneNumbers = personElement.Elements("Phone");
This means you don't need to have intermediate elements like <Phones> or <EmailAddresses>, you'd only add them if it was necessary to introduce attributes/metadata covering groups of child elements.
精彩评论