mishmash
mishmash

Reputation: 4458

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.

Upvotes: 0

Views: 208

Answers (3)

default
default

Reputation: 11635

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)
    )
);

Upvotes: 0

Mark
Mark

Reputation: 2432

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

Upvotes: 0

Roy Dictus
Roy Dictus

Reputation: 33139

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?

Upvotes: 1

Related Questions