Monday, July 31, 2006

C#: Why does XmlElement need to know the XmlDocument up front?

When I build up XML object trees I like to start small and assemble them. So, for example, if I've got a Record which contains a Summary, a Person, and a bunch of Transaction objects, then maybe I'll go off to the Person class and set up a way for it to generate itself as an XML Element. Do the same with all of them, and then the Record just becomes a bunch of nested calls to Person.toXML(), and so on.

Normally I do this in Java. I'm particularly fond of creating a functional-esque BuilderElement class which keeps returning itself so that I can easily do things like BuilderElement.create("Student").addElement("Name").addElement("First").addText("Duane") because I'm lazy like that. You can't easily nest too deep, because you'll lose references to your middle objects (for instance, it would be hard to go back and add "Middle" name unless I established a pointer to the Name element. But I much prefer it for quick situations where I'm more deep than wide. That is, most elements have only one child, not a bunch.

A new project requires that I learn C#, so I'm digging in to the System.Xml ... thing. Package. Namespace. Whatever they're called. And what I'm learning is that in order to create an XmlElement, I need to have an XmlDocument already created. Either I call xmldoc.CreateElement(...) or else I have to pass it in as a parameter, ala new XmlElement(..., xmldoc). Don't know why that is. But I don't love it.

No real revelations here, just throwing it out there. Curious if anybody knows why you'd need to have your XmlDocument created before your XmlElement. I mean, I understand the logic that an XmlElement isn't really useful unless nested in an XmlDocument, but what's the actual reason why it is mandated like that?



Technorati Tags: