【问题标题】:How to add Xml attribute to a property at runtime如何在运行时将 Xml 属性添加到属性
【发布时间】:2019-08-28 15:23:22
【问题描述】:

我需要将一个类序列化为 xml。如果在运行时满足某个条件,我想将 XML 属性添加到元素并为其分配一个值。有时,“错误”属性会出现,有时不会。

序列化我的对象的代码:

public class XmlToolsRepo : IXmlTools
{
    public string SerializeToXML<T>(object obj)
    {
        string results = null;

        Encoding enc = Encoding.UTF8;
        using (MemoryStream ms = new MemoryStream())
        {
            using (XmlTextWriter xw = new XmlTextWriter(ms, enc))
            {
                xw.Formatting = Formatting.None;
                XmlSerializerNamespaces emptyNS = new XmlSerializerNamespaces(new[] { new XmlQualifiedName("", "") });
                XmlSerializer xSerializer = new XmlSerializer(typeof(T));
                xSerializer.Serialize(xw, obj, emptyNS);
            }

            results = enc.GetString(ms.ToArray());
        }

        return results;
    }
}

具有在运行时可能具有新属性的属性的类:

[DataContract]
public class H204
{
    [DataMember]
    [XmlAttribute]
    public string Code { get; set; }

    [DataMember]
    public string DW { get; set; }
}

当满足条件时,我需要 XML 看起来像这样:

<?xml version="1.0" encoding="UTF-8"?>
<H204 Code="A">
    <DW Error="test" />
</H204>

【问题讨论】:

标签: c# xml


【解决方案1】:

尝试以下:

    public class H204
    {
        [XmlAttribute(AttributeName = "Code")]
        public string Code { get; set; }

        [XmlElement(ElementName = "DW")]
        public  DW  dw{ get; set; }
    }
    public class DW
    {
        [XmlAttribute(AttributeName = "Error")]
        public string text { get; set; }
    }

【讨论】:

  • 这太完美了,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-02
  • 2019-04-27
  • 1970-01-01
  • 1970-01-01
  • 2012-09-16
  • 2018-03-24
  • 2013-06-14
相关资源
最近更新 更多