www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Storing arbitrary type info in XML

reply "F i L" <witte2008 gmail.com> writes:
I'm trying to store arbitrary D object information in an XML 
file, then load and create the objects it represents 
programmatically. For example, I have the file test.xml, which 
looks like:

     <!-- test.xml -->
     <scene>
       <main.Person name="Philip" age="24">
           <!-- nothing yet -->
       </main.Person>
     </scene>

and corresponds to the D file:

     // main.d
     import std.conv, std.stdio;
     import std.file, std.xml;

     class Person {
       string name;
       uint age;
     }

     void main() {
       // 1. read XML file, create Document
       // 2. create objects named in Document
       // 3. set objects data based on attributes
     }

currently I'm accomplishing this by using Object.factory() and 
casting it to Person to see if it's a person; then run each XML 
attribute through a switch statement which sets the Person fields 
accordingly.

I can generate all that, which makes it a bit more dynamic, but 
is that really the best way to go about this? It seems too rigid 
for my tastes (can't create structs) and, when lots of objects 
are potentially represented, slow as well.


I was thinking of using generated D files instead of XML which 
was an interesting concept except a bit limiting in other ways.

Does anyone have any thoughts on any of this. I'd love to know 
them if you do :)
May 07 2012
parent "Adam D. Ruppe" <destructionator gmail.com> writes:
Here's one way you could do it:

http://arsdnet.net/dcode/xmlthing.d

You have to add the various classes to your
thing for it to build the reflection info.

That's the beginning of main() (bottom of
file).


I used the delegate map for the members
up top, which is a bit weird looking code
but is able to set anything at runtime,
which it uses to build the map.

I used my dom.d as the xml lib because I don't
know std.xml, but it shouldn't be too hard to
change over since it doesn't do anything fancy.

If you want my library though, it is in here:
https://github.com/adamdruppe/misc-stuff-including-D-programming-language-web-stuff

dom.d and characterencodings.d
May 08 2012