简体   繁体   中英

XmlSerializer serialize class contents

I have two classes, lets call them A and B :

public class A
{
    public int foo;
    public int bar;
}

public class B
{
    public class A;
}

Now when I serialize object B the XmlSerializer is doing what you expect it to do:

<?xml version="1.0" encoding="utf-8"?>
<B>
    <A>
        <foo>0</foo>
        <bar>0</bar>
    </A>
</B>

But I would need the XmlSerializer to serialize the contents of class A but ignore the root <A> tag, like so:

<?xml version="1.0" encoding="utf-8"?>
<B>
    <foo>0</foo>
    <bar>0</bar>
</B>

I know I could just put the members of A into B but these are big classes and I would like that to be the last resort. I have tried to search MSDN/Google/the Internet but I just cant seem to get the wording right to find meaningful results so sorry if this has been asked before.

Is there any way to make the XmlSerializer not write the root tag of the class but write its members anyway? Preferably without reorganizing classes, but if there is no other way, I will do that, too.

The XmlSerializer is not that flexible -- you can tell it to ignore a property, but then it ignores it completely.

Mind you, anything you would serialize this way would be hard if not impossible to correctly deserialize again later.

Why don't you just put foo and bar as properties of B instead?

What about:

public class A
{
    public int foo;
    public int bar;
}

public class B
{
    [XmlElement(ElementName = "ABetterName")]
    public A Inner;
}

Although this is not what you're looking for it may be preferable as it allows you to give better names to the elements

You can use XDocument and build the XML yourself.
Something like:

XDocument doc = new XDocument(
    new XElement("B",
        new XElement("foo", a.foo),
        new XElement("bar", a.bar)
    )
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM