C#中的XmlSerializer,反序列化由多个具有相同名称的特定属性的XmlElement修饰的类?

时间:2017-04-26 09:57:38

标签: c# xml deserialization xmlserializer xml-attribute

我有一个以错误的方式用XmlElement修饰的类,但它也有一些属性可以让我识别我需要的字段。

我只能修改[IWantToSerializeThisAttribute]并将其他属性添加到MySerializableClass,因为对属性名称或XmlElement名称的任何修改都会涉及大量的编码维护。

以下是该类的定义方式:

 [XmlRoot("ARandomXmlRoot")]
    public class MySerializableClass
    {

        //CAMPI DIR_DOCUMENTI
        //[MetadatoDocumentoAlfresco] è un attributo che serve per selezionare i campi per l'aggiornamento dati massivo su alfresco
        [IWantToSerializeThisAttribute]
        [XmlElement("DocumentCode")]
        public string DOC_CODE { get; set; }

        [IWantToSerializeThisAttribute]
        [XmlElement("DocumentId")]
        public string DOC_ID { get; set; }

        [XmlElement("DocumentCode")]
        public string DOC_CODE_FOR_EMPLOYEES { get; set; }

        [XmlElement("DocumentId")]
        public string DOC_ID_FOR_EMPLOYEES { get; set; }

    }

现在,如果我这样做

XmlSerializer.Deserialize(xmlString, typeof(MySerializableClass));

我最有可能得到一个错误,因为XmlSerializer找到了2次

[XmlElement("DocumentCode")]

并且看到它是重复的标签。

无论如何我有一个

[IWantToSerializeThisAttribute]

使2个属性不同。

我可以告诉XmlSerializer.Deserialize只捕获和定价“IwantToSerializeThisAttribute”属性并忽略其他属性吗?

我无法使用XmlOverrideAttributes更改序列化,但在反序列化期间可能有一些方法可以执行此操作。

谢谢大家

2 个答案:

答案 0 :(得分:1)

尝试使用XmlOverrideAttributes和Reflection。使用LINQ只是为了缩短它。

这对我有用:

 string XmlString = "<ARandomXmlRoot> XML HERE </ARandomXmlRoot>";
            XmlAttributeOverrides overrides = new XmlAttributeOverrides();

            //Select fields I DON'T WANT TO SERIALIZE because they throw exception
            string[] properties = (new MySerializableClass())
                .GetType().GetProperties()
                .Where(p => !Attribute.IsDefined(p, typeof(IWantToSerializeThisAttribute)))
                .Select(p => p.Name);

            //Add an XmlIgnore attribute to them
            properties.ToList().ForEach(field => overrides.Add(typeof(MySerializableClass), field, new XmlAttributes() { XmlIgnore = true }));

            MySerializableClass doc = new MySerializableClass();

            XmlSerializer serializerObj = new XmlSerializer(typeof(MySerializableClass), overrides);
            using (StringReader reader = new StringReader(xmlString))
            {
                doc = (MySerializableClass)serializerObj.Deserialize(reader);
            };

干杯

答案 1 :(得分:0)

不确定我是否理解正确,但让我尝试给你一些选择:

  

我可以告诉XmlSerializer.Deserialize只能捕获和定价&#34; IwantToSerializeThisAttribute&#34;属性而忽略其他属性?

如果只想序列化特定属性,请使用[XmlIgnore]属性作为要省略的属性。但如果由于某种原因(DOC_CODE_FOR_EMPLOYEESDOC_ID_FOR_EMPLOYEES

但如果你的意思是在反序列化时只应省略它,但仍应对所有属性进行序列化,我会考虑实现IXmlSerializable。这样您就可以专门提供读/写xml的方式。

相关问题