2009-12-30 114 views
2

我有一个类,我需要做一些自定义的XML输出,因此我实现了IXmlSerializable接口。但是,我想用默认序列化输出一些字段,但我想更改xml标记名称。当我调用serializer.Serialize时,我得到了XML中的默认标签名称。我可以改变这些吗?自定义序列化使用XmlSerializer

这里是我的代码:

public class myClass: IXmlSerializable 
{ 
    //Some fields here that I do the custom serializing on 
    ... 

    // These fields I want the default serialization on except for tag names 
    public string[] BatchId { get; set; } 
    ... 

    ... ReadXml and GetSchema methods are here ... 

    public void WriteXml(XmlWriter writer) 
    {       
     XmlSerializer serializer = new XmlSerializer(typeof(string[])); 
     serializer.Serialize(writer, BatchId); 
     ... same for the other fields ... 

     // This method does my custom xml stuff 
     writeCustomXml(writer); 
    } 

    // My custom xml method is here and works fine 
    ... 
} 

这里是我的XML输出:

<MyClass> 
    <ArrayOfString> 
     <string>2643-15-17</string> 
     <string>2642-15-17</string> 
     ... 
    </ArrayOfString> 
    ... My custom Xml that is correct .. 
    </MyClass> 

我想直到结束是:

<MyClass> 
    <BatchId> 
     <id>2643-15-17</id> 
     <id>2642-15-17</id> 
     ... 
    </BatchId> 
    ... My custom Xml that is correct .. 
    </MyClass> 
+0

多久你序列化/反序列化?在应用生命周期内或仅在启动/关闭期间执行100次。如果前者我有一个更灵活的实现。 – 2009-12-30 20:30:59

+0

真的只有序列化一次。这个应用程序是一个简单的工具,它从专有数据库格式中提取数据并保存到xml。所以我将数据拉入对象模型,然后立即序列化。大部分数据很简单,所以我不需要实现IXmlSerializable ...但是这个特定的数据有点痛苦。 – KrisTrip 2009-12-30 20:34:50

+0

看看这里,代码是MIT http://code.google.com/p/videobrowser/source/browse/MediaBrowser/Library/Persistance/XmlSettings.cs还有一个单元测试,你可能不得不扩展一下,但所有的架构都在那里。加上你的场景,它会比XmlSerializer更好地执行 – 2009-12-30 20:41:23

回答

7

在很多情况下,你可以使用XmlSerializer构造函数重载接受XmlAttributeOverrides指定此额外的名字信息(例如,通过一个新的XmlRootAttribute) - 但是,这并不对数组工作AFAIK。我期望string[]的例子,只是手动编写它会更简单。在大多数情况下,IXmlSerializable是很多额外的工作 - 我尽可能避免这样的原因。抱歉。

+0

XmlSerializer是一种老旧的无用的低效技术,应该在MS之前被MS弃用,或者在最低限度重新实现。我只是遇到了麻烦。更好的使用协议缓冲区:p – 2009-12-30 20:29:39

+0

看看我是否可以将pb-net的输出转换为xml; -p – 2009-12-30 20:41:46

+0

你应该完全做到这一点,并使其可以插入,以便人们可以实现自己的持久性格式,然后你甚至可以使用sqlite作为数据存储... – 2009-12-30 20:48:58

3

你可以标记您的领域属性为control the serialized XML。例如,添加以下属性:

[XmlArray("BatchId")] 
[XmlArrayItem("id")] 
public string[] BatchId { get; set; } 

可能会让你那里。

+1

试过了。没有运气。 – KrisTrip 2009-12-30 20:12:57

0

如果有人仍然在寻找这个,你可以肯定地使用XmlArrayItem,但是这需要是一个类中的一个属性。

为便于阅读,您应该使用同一个词的复数和单数。

/// <summary> 
    /// Gets or sets the groups to which the computer is a member. 
    /// </summary> 
    [XmlArrayItem("Group")] 
    public SerializableStringCollection Groups 
    { 
     get { return _Groups; } 
     set { _Groups = value; } 
    } 
    private SerializableStringCollection _Groups = new SerializableStringCollection(); 



<Groups> 
    <Group>Test</Group> 
    <Group>Test2</Group> 
</Groups> 

大卫