Search code examples
c#-4.0linq-to-xmlxelement

How do I know if I need an XDocument or XElement?


I understand that they are very similar and that the XDocument represents a whole document and an XElement represents a fragment of a whole document, but they seem to be very similar when it comes to loading and querying/updating the data. I am going to have templates saved to a disk and when I load them, I want to query over them and insert,update, and delete sections of data be it attributes or elements. Does XDocument or XElement make a difference here? Does it make a difference if I build the template on the dynamically first?


Solution

  • For starters, they behave in a different way when loading a document, which means you'll have to write your queries in a different way when you choose one over the other. Except for that, msdn states that

    The XDocument class contains the information necessary for a valid XML document. This includes an XML declaration, processing instructions, and comments. Note that you only have to create XDocument objects if you require the specific functionality provided by the XDocument class. In many circumstances, you can work directly with XElement. Working directly with XElement is a simpler programming model

    So I'd stick to XElement, unless any of above mentioned metadata about xml is needed (which doesnt seem to be the case).