2

I am currently trying to write a program in D that when called and passed an object, it will serialize the object into an XML document. I would like to make it as simple as passing the object into it, but I'm not entirely sure it can be done. Example:

class A
{
    //Constructors and fluff
    ....

    int firstInt;
    int secondInt;
}

.....
A myObj = new A();
XMLSerialize(myObj);

and the output would be

<A.A>
    <firstInt></firstInt>
    <secondInt></secondInt>
</A.A>

So, is it possible for me to even get the name of the variables inside of the object or would that have to all be manually done?

4

3 回答 3

6

代码值一千字(特意简化):

import std.stdio;

void print(T)(T input)
    if (is(T == class) || is(T == struct))
{
    foreach (index, member; input.tupleof)
    {
        writefln("%s = %s", __traits(identifier, T.tupleof[index]), member);
    }
}

struct A
{
    int x, y;
}

void main()
{
    print(A(10, 20));
}
于 2013-11-28T22:22:51.843 回答
2

stingof 不是合适的答案。std.traits 中有一些东西可以做更多你所期望的事情。一般地做你想做的事有点像,但你可以使用编译时反射来为你想要的任何类生成序列化程序。

https://github.com/msgpack/msgpack-d 这样做。

还:

https://github.com/Orvid/JSONSerialization/blob/master/JSONSerialization/std/serialization/xml.d

于 2013-11-28T21:57:58.557 回答
1

.stringof返回一个带有变量名的字符串。

void main()
{
    int some_int;
    assert(some_int.stringof == "some_int");
}
于 2013-11-28T20:30:31.033 回答