在元素中将属性序列化为 Xml 属性

我有以下课程:

[Serializable]
public class SomeModel
{
[XmlElement("SomeStringElementName")]
public string SomeString { get; set; }


[XmlElement("SomeInfoElementName")]
public int SomeInfo { get; set; }
}

当使用 XmlSerializer. Serialize ()填充一些测试数据并进行序列化时,将生成以下 XML:

<SomeModel>
<SomeStringElementName>testData</SomeStringElementName>
<SomeInfoElementName>5</SomeInfoElementName>
</SomeModel>

我需要的是:

<SomeModel>
<SomeStringElementName Value="testData" />
<SomeInfoElementName Value="5" />
</SomeModel>

有没有办法不用编写自己的自定义序列化代码就可以将其指定为属性?

139170 次浏览

类似地,使用 XmlAttribute而不是 XmlElement,但它看起来不像您想要的那样。它看起来会像下面这样:

<SomeModel SomeStringElementName="testData">
</SomeModel>

我能想到的实现您想要(本地)的唯一方法是让属性指向名为 Some StringElementName 和 Some InfoElementName 的对象,其中类包含一个名为“ value”的 getter。您可以进一步使用 DataContractSerializer,以便包装器类可以是私有的。XmlSerializer 不会读取私有属性。

// TODO: make the class generic so that an int or string can be used.
[Serializable]
public class SerializationClass
{
public SerializationClass(string value)
{
this.Value = value;
}


[XmlAttribute("value")]
public string Value { get; }
}




[Serializable]
public class SomeModel
{
[XmlIgnore]
public string SomeString { get; set; }


[XmlIgnore]
public int SomeInfo { get; set; }


[XmlElement]
public SerializationClass SomeStringElementName
{
get { return new SerializationClass(this.SomeString); }
}
}

您将需要包装类:

public class SomeIntInfo
{
[XmlAttribute]
public int Value { get; set; }
}


public class SomeStringInfo
{
[XmlAttribute]
public string Value { get; set; }
}


public class SomeModel
{
[XmlElement("SomeStringElementName")]
public SomeStringInfo SomeString { get; set; }


[XmlElement("SomeInfoElementName")]
public SomeIntInfo SomeInfo { get; set; }
}

如果你愿意,也可以选择一种更通用的方法:

public class SomeInfo<T>
{
[XmlAttribute]
public T Value { get; set; }
}


public class SomeModel
{
[XmlElement("SomeStringElementName")]
public SomeInfo<string> SomeString { get; set; }


[XmlElement("SomeInfoElementName")]
public SomeInfo<int> SomeInfo { get; set; }
}

然后:

class Program
{
static void Main()
{
var model = new SomeModel
{
SomeString = new SomeInfo<string> { Value = "testData" },
SomeInfo = new SomeInfo<int> { Value = 5 }
};
var serializer = new XmlSerializer(model.GetType());
serializer.Serialize(Console.Out, model);
}
}

会产生:

<?xml version="1.0" encoding="ibm850"?>
<SomeModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<SomeStringElementName Value="testData" />
<SomeInfoElementName Value="5" />
</SomeModel>