2010-09-27 48 views
0

改變序列化的XML元素的標籤名稱一些背景資料:如何通過IXmlSerializable的

我們有一些實體類需要被序列化,所以我們實現實體類如第一版如下:

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

序列化的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> 

但是,我們需要做的Text屬性爲只讀,所以我們改變了Foo類實現IXmlSeri alizable界面如下:

[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); 
    } 
} 

然後序列化的XML字符串也改爲如下:

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

有沒有辦法改變從「<Foo>foo</Foo>」到「<FooElement>foo</FooElement>」標籤的名字嗎?

回答

2

我猜想,XmlRootAttribute應該和IXmlSerializable一起玩。

+0

謝謝,XmlRootAttribute按預期工作。 – 2010-09-27 08:13:43