开发者

Tweak output from XmlSerializer in C#

开发者 https://www.devze.com 2023-04-02 06:08 出处:网络
I am wondering if there is a way to get XmlSerializer in C# to change what it outputs for one property of one object.For example, if I have something like:

I am wondering if there is a way to get XmlSerializer in C# to change what it outputs for one property of one object. For example, if I have something like:

public class MyClass
{
    public string prop1{get;}
    public uint prop2{get;}
    public MyClass2 class2{get;}
    public MyClass3 class3{get;}
}

public class MyClass2
{
    public string prop3{get;}
}

public class MyClass3
{
    //Lots of properties that I want to serialize as normal
}

Now in somewhere in my code, I have something like this:

private void SerializeStuff(List<MyClass> list, string path)
{
    XmlSerializer serialize = new XmlSerializer(typeof(List<MyClass>));
    TextWriter writer = new StreamWriter(path);
    serialize.Serialize(writer, list);
    writer.Close();
}

What I want is for the serialization to work as normal, but with prop3 replaced with some other stuff. Example:

<MyClass>
    <prop1>whatever</prop1>
    <prop2>345</prop2>
    <class2>
        <somethingNotProp3>whatever</something开发者_运维知识库NotProp3>
        <somethingElseNotProp3>whatever</somethingElseNotProp3>
    </class2>
    <class3>
        ...
    </class3>
</MyClass>

Is there a way to customize XmlSerializer so I don't have to write the entire Xml file manually, or is there no way to do that?

Edit: I am pretty sure that the solution could have something to do with implementing ISerializable's GetObjectData method; however, I am not exactly sure how to implement it. I tried making MyClass2 inherit from ISerializable and implementing GetObjectData, but nothing changed. prop3 was still output in the XML file.


Use the attributes in the System.Xml.Serialization namespace to affect the way that the instance is serialized.

If you need very specialized serialization for MyClass3 that the attributes cannot handle, then implement the IXmlSerializable interface which will give you complete control over the serialization process (you can even decide on an instance-by-instance basis how to serialize the content/property).

Based on the comments, it would seem that you want to implement IXmlSerializable, as you want to change the name of the property and the value; the attributes will let you change the name of the property/element/attribute, but not allow you to perform transformations on the value (and I assume you don't want to corrupt your representation and add an extra property/value for this purpose).

0

精彩评论

暂无评论...
验证码 换一张
取 消