benderman
benderman

Reputation: 103

Xml serialization remove inner tags

I'm having a bit of trouble getting the desired xml serialization that I want. Thanks beforehand for your help.

So, the xml that I am aiming for looks something like this:

<ChangeSet>
    <Change class="object" key="foo">
        bar
    </Change>
    <Change class="testing" key="temp">
        temp
    </Change>
</ChangeSet>

What I'm actually getting is:

<ChangeSet>
    <Change class="object" key="foo">
        <Value> bar </Value>
    </Change>
    <Change class="testing" key="temp">
        <Value> temp </Value>
    </Change>
</ChangeSet>

Note that the value inside of the Value tags need to be able to be any object. (Collection, object, generic type... etc) How can I get rid of the Value tags?

C# code:

[Serializable]
[XmlRoot("ChangeSet")]
public class ChangeSet
{
    [XmlElement("Change", typeof(Change))]
    public List<Change> Changes;
}
public class Change
{
    [XmlAttribute("Class")]
    public string Class;

    [XmlAttribute("Description")]
    public string Key;

    public object Value;
}


StringBuilder xml = new StringBuilder();
XmlSerializer serializer = new XmlSerializer(objToSerialize.GetType());
XmlWriterSettings settings = new XmlWriterSettings()
{
    OmitXmlDeclaration = true,
    Indent = true
};

using (StringWriter writer = new StringWriter(xml))
{
    using (XmlWriter xmlWriter = XmlWriter.Create(writer, settings))
    {
        XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
        ns.Add("", ""); // Removes the xsd & xsi namespace declarations from the xml
        serializer.Serialize(xmlWriter, objToSerialize, ns);
    }
}

Upvotes: 0

Views: 1061

Answers (1)

Amit
Amit

Reputation: 126

Use [XmlText] attribute over Value of type string

[XMLText]
public string Value;

or use another string property and ignore the Value property

[XMLIgnore]
public object Value;

[XMLText]
public string ValueString
{
  get{ return this.Value.ToString(); }
}

Upvotes: 1

Related Questions