反序列化xml时,输入字符串的格式不正确

时间:2016-03-09 17:42:29

标签: c# xml serialization deserialization

我有一个奇怪的问题。我有这个Xml

<?xml version="1.0" encoding="utf-8"?>
<Facilities RunTime="2016-03-09 14:18:11">
<Facility ID="789">
    <Name>Facility 4</Name>
    <Contact />
    <AreaName>Center</AreaName>
    <MunicipalCode>453</MunicipalCode>
    <SMSInfo />
    <Materials />
  </Facility>
  <Facility ID="-1">
    <Name>Facility 2</Name>
    <Contact />
    <AreaName>Mark</AreaName>
    <MunicipalCode />
    <SMSInfo />
    <Materials />
  </Facility>
</Facilities>

当我尝试反序列化这个xml时,它在标记<MunicipalCode />上为空时失败(参见第二个根设施中的元素MunicipalCode)   但不在<MunicipalCode>453</MunicipalCode>(在第一个根目录中),所以当我将空的一个更改为<MunicipalCode>test test </MunicipalCode>时,它就不会失败

这是我的模型,我试图处理这个值,以防它变为null。

[Table("FacilityNew")]
    public class FacilityNew
    {

        [XmlAttribute("ID"), Key]
        public int Id { get; set; }

        [XmlElement("SMSInfo")]
        public virtual SMSInfo smsInfos { get; set; }

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

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

        [XmlElement("AreaName")]
        public string AreaNameID { get; set; }

        [XmlIgnore]
        public string MunicipalCode { get; set; }

        [XmlElement("MunicipalCode")]
        [Browsable(false)] // not displayed in grids
        [EditorBrowsable(EditorBrowsableState.Never)] // not displayed by intellisense
        public string MunicipalCodeStirng
        {
            get
            {
                if ((MunicipalCode) != null)
                {
                    return MunicipalCode;
                }
                else
                    return "";
            }
            set
            {
                if ((value)!=null)
                {
                    MunicipalCode = value;
                }
                else
                {
                    MunicipalCode = "";
                }
            }
        }

        [XmlArray("Materials")]
        [XmlArrayItem("Material")]
        public virtual List<Material> Materials { get; set; }

        public FacilityNew()
        {
            this.Materials = new List<Material>();
        }
    }

但它仍然失败   它很奇怪,因为其他空标签不会失败,我得到的输入字符串格式不正确&#34;如果我将此标记的名称更改为<MunicipalCodeASDF />或其他内容,则不会失败。

这就是我反序列化的方式,

 XmlSerializer deserializer = new XmlSerializer(typeof(FacilityNew));
           StreamReader sr = new StreamReader(path);
            allaFacilities = (FacilityNew)deserializer.Deserialize(sr);

问题是什么

1 个答案:

答案 0 :(得分:1)

通过在反序列化器中添加正则表达式来解决问题

build.gradle