2011-05-19 33 views
3

我试图序列化一个对象以满足另一个系统需求。在.net中的XML序列化

它需要看起来像这样:

<custom-attribute name="Colour" dt:dt="string">blue</custom-attribute> 

,而是正在寻找这样的:

<custom-attribute>blue</custom-attribute> 

到目前为止,我有这样的:

[XmlElement("custom-attribute")] 
public String Colour{ get; set; } 

我不是真的确定我需要什么元数据来实现这一点。

回答

2

您可以实现IXmlSerializable

public class Root 
{ 
    [XmlElement("custom-attribute")] 
    public Colour Colour { get; set; } 
} 

public class Colour : IXmlSerializable 
{ 
    [XmlText] 
    public string Value { get; set; } 

    public XmlSchema GetSchema() 
    { 
     return null; 
    } 

    public void ReadXml(XmlReader reader) 
    { 
     throw new NotImplementedException(); 
    } 

    public void WriteXml(XmlWriter writer) 
    { 
     writer.WriteAttributeString("dt:dt", "", "string"); 
     writer.WriteAttributeString("name", "Colour"); 
     writer.WriteString(Value); 
    } 
} 

class Program 
{ 
    static void Main() 
    { 
     var serializer = new XmlSerializer(typeof(Root)); 
     var root = new Root 
     { 
      Colour = new Colour 
      { 
       Value = "blue" 
      } 
     }; 
     serializer.Serialize(Console.Out, root); 
    } 
} 
+0

这太难了基于我需要做的自定义XML的量来实现。所以我创建了一个更简单的黑客解决方案。这看起来是正确的。谢谢 – 2011-05-26 04:30:15