Hondros Hondros - 1 month ago 11
C# Question

C# XML Serialize without a wrapper

I have the following class fragment:

public class varString
{
public string KeyWord;
public string Value;
public static implicit operator string(varString v)
{
return v == null ? null : (string)v.Value;
}
}


KeyWord is allowed to be null.

When serializing to XML, I get the following output when KeyWord is null:

<varString>
<Value>value goes here</Value>
</varString>


How can I get the XML serializer to output the following when and only when KeyWord is null?:

<varString>value goes here</varString>


If KeyWord is not null, I'd still like it to output the following:

<varString>
<!-- Can either be <Value></Value or just straight text -->
<KeyWord>KeyWord goes here</KeyWord>
<varString>


Please note that I have already modified the deserialize events to handle this case to convert the lone string into a varString with a null KeyWord.

dbc dbc
Answer

Mark Value with the attribute [XmlText]:

public class varString
{
    [XmlText]
    public string Value;
    public string KeyWord;
    public static implicit operator string(varString v)
    {
        return v == null ? null : (string)v.Value;
    }
}

Sample fiddle.

Comments