没有包装器的{C#XML Serialize

时间:2016-11-02 19:44:08

标签: c# xml

我有以下类片段:

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

允许KeyWord为null。

当序列化为XML时,当KeyWord为null时,我得到以下输出:

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

当且仅当KeyWord为null时,如何让XML序列化程序输出以下内容?:

<varString>value goes here</varString>

如果KeyWord不为null,我仍然希望输出以下内容:

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

请注意,我已经修改了deserialize事件来处理这种情况,将单独的字符串转换为带有空KeyWord的varString。

2 个答案:

答案 0 :(得分:1)

使用属性[XmlText]标记Value

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

示例fiddle

答案 1 :(得分:0)

尝试这种方法:

var vs = new varString();
vs.KeyWord = "key"; // null;
vs.Value = "value";


var attr = new XmlAttributes();

if (vs.KeyWord == null)
    attr.XmlText = new XmlTextAttribute();
else
    attr.XmlElements.Add(new XmlElementAttribute { ElementName = "Value" });

var overrides = new XmlAttributeOverrides();
overrides.Add(typeof(varString), "Value", attr);


var xs = new XmlSerializer(typeof(varString), overrides);
xs.Serialize(Console.Out, vs);

我们根据KeyWord值添加XmlTextAttributeXmlElementAttribute