简体   繁体   English

如何通过IXmlSerializable更改序列化XML元素的标记名

[英]How to change the tag name of the serialized XML element via IXmlSerializable

Some background: 一些背景:

We have some entity classes need to be serialized, so we implement the entity class as following in the first edition: 我们有一些实体类需要序列化,因此我们在第一版中实现了以下实体类:

[XmlType("FooElement")]
public class Foo
{
    [XmlText]
    public string Text { get; set; }
}

The serialized XML string should be: 序列化的XML字符串应为:

<?xml version="1.0" encoding="gb2312"?>
<FooElement xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" mlns:xsd="http://www.w3.org/2001/XMLSchema">foo</FooElement>

But we need to make the Text property as read only, so we change the Foo class to implement the IXmlSerializable interface as following: 但是我们需要将Text属性设置为只读,因此我们更改Foo类以实现IXmlSerializable接口,如下所示:

[Serializable]
public class Foo : IXmlSerializable
{
    public Foo()
    { }

    public Foo(string text)
    {
        Text = text;
    }

    public string Text { get; private set; }

    public XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(XmlReader reader)
    {
        Text = reader.Value;
    }

    public void WriteXml(XmlWriter writer)
    {
        writer.WriteValue(Text);
    }
}

Then the serialized XML string was also changed as following: 然后,序列化的XML字符串也进行了如下更改:

<?xml version="1.0" encoding="gb2312"?><Foo>foo</Foo>

Is there any way to change the tag name from " <Foo>foo</Foo> " to " <FooElement>foo</FooElement> "? 有什么方法可以将标记名称从“ <Foo>foo</Foo> ”更改为“ <FooElement>foo</FooElement> ”?

我猜想, XmlRootAttribute应该可以与IXmlSerializable一起很好地发挥作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM