c# - .net 中的 XML 序列化

标签 c# .net xml xmlserializer

我正在尝试序列化一个对象以满足另一个系统要求。

它需要看起来像这样:

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

而是看起来像这样:

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

到目前为止我有这个:

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

我不太确定实现此目标需要哪些元数据。

最佳答案

你可以实现 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);
    }
}

关于c# - .net 中的 XML 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6055140/

相关文章:

c# - 您可以在字典的 ValueTuple 值中声明项目名称吗?

.NET:System.IO.Path

javascript - IE8中如何获取XML节点的文本值?

c# - Windows Phone 7,silverlight - 如何在调用异步 Web 服务时捕获 EndpointNotFoundException?

.net - .NET 库中是否有稀疏数组实现?

xml - JAXB 2 spring-ws 2.0.3.RELEASE SOAP 服务教程链接/建议请求

java - 通用图像加载器 imageview 不会使用微调器自行更新

c# - 如何在 .NET Standard 中为通用枚举类型设置枚举标志?

c# - 目标框架版本为 4.7.2 的 C# 项目可以在 .net 4.6.1 上运行吗

c# - GridView 中的下拉列表