XML子元素反序列化抛出InvalidOperationException

时间:2013-04-16 16:58:49

标签: c# xml ixmlserializable

我正在尝试手动反序列化数据对象的层次结构(下面的完整代码),但是获得了一个我不理解的异常。

  • DEMDataSet包含DemographicReportGroup个对象的集合。
  • DemographicReportGroup实现IXmlSerializable,包含Agency对象。
  • Agency对象包含叶数据项dAgency.01,又名EMSAgencyUniqueStateID

我正在为ReadXml实现DemographicReportGroup方法,但是我得到了一个异常,如下所示:

#region ReadXml
public void ReadXml(System.Xml.XmlReader xmlReader)
{
    xmlReader.MoveToContent();
    this.timeStamp = DateTime.Parse(xmlReader.GetAttribute("timeStamp"));
    if (xmlReader.IsEmptyElement) return;
    xmlReader.ReadStartElement();
    if (xmlReader.Name == "dAgency") 
    { 
        xmlReader.ReadStartElement("dAgency");
        // **Exception here: System.InvalidOperationException**
        this.Agency = new XmlSerializer(typeof(Agency)).Deserialize(xmlReader) as Agency; 
        xmlReader.ReadEndElement(); 
    }
    xmlReader.ReadEndElement();
}
#endregion
  

System.InvalidOperationException:< dAgency.01 xmlns ='http://www.nemsis.org'>没想到。

到目前为止我发现的所有代码示例都表明这应该有用......也许是XML属性的错误配置?

希望有人可以提供帮助!

另外,如果你很好奇:

  • 为什么要实施IXmlSerializable
    • timeStamp属性是日期/时间。如果它是普通的DateTime,它在序列化时总是有一个值(1/1/0001)。 DateTime?类型让我知道它何时没有值,但不能将其序列化为属性。此示例所属的数据标准规定时间戳 必须 为属性。
  • 如何实施ShouldSerializetimeStampValue?
    • 这会产生额外的属性和额外的方法(timeStampValue和ShouldSerializetimeStampValue),这对于一个数据项来说代码太多了。此外,这不是我正在处理的唯一时间戳。

完整代码(作为Visual Studio的单元测试):

using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;  // System.Xml.dll.
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Tests.Xml
{
    [TestClass]
    public class TestIXmlSerializable
    {
        [TestMethod]
        public void DeserializeChildElement()
        {
            var xml = @"<DEMDataSet xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xsi:schemaLocation=""http://www.nemsis.org http://nemsis.org/media/XSD_v3/_nemsis_v3.3.1/3.3.1.130201/XSDs/NEMSIS_XSDs_v3.3.1.130201/DEMDataSet_v3.xsd""  xmlns=""http://www.nemsis.org"">
    <DemographicReport timeStamp=""1969-03-14T07:38:20+07:00"">
        <dAgency>
            <dAgency.01>M</dAgency.01>
        </dAgency>
    </DemographicReport>
</DEMDataSet>";

            var xmlSerializer = new XmlSerializer(typeof(DEMDataSet));

            DEMDataSet demDataSet = null;

            using (var streamReader = new StringReader(xml))
                demDataSet = xmlSerializer.Deserialize(streamReader) as DEMDataSet;

        }
    }

    [Serializable]
    /// <summary>Root Tag For Demographic DataSet</summary>
    [XmlType(AnonymousType = true, Namespace = "http://www.nemsis.org")]
    [XmlRoot(Namespace = "http://www.nemsis.org", IsNullable = false)]
    public partial class DEMDataSet
    {
        #region DemographicReportGroup
        private List<DemographicReportGroup> _demographicReportGroup;

        /// <summary>Container Tag to hold each instance of a demographic record</summary>
        [XmlElement("DemographicReport")]
        public List<DemographicReportGroup> DemographicReportGroup
        {
            get
            {
                return this._demographicReportGroup;
            }
            set
            {
                this._demographicReportGroup = value;
            }
        }
        #endregion

    }

    [Serializable]
    public partial class DemographicReportGroup : IXmlSerializable
    {
        #region Agency
        private Agency _agency;

        /// <summary></summary>
        [XmlElement("dAgency", IsNullable = false)]
        public Agency Agency
        {
            get
            {
                return this._agency;
            }
            set
            {
                this._agency = value;
            }
        }
        #endregion

        #region timeStamp
        private DateTime? _timeStamp;

        /// <summary></summary>
        [XmlAttribute]
        public DateTime? timeStamp
        {
            get
            {
                return this._timeStamp;
            }
            set
            {
                this._timeStamp = value;
            }
        }
        #endregion

        #region GetSchema
        public System.Xml.Schema.XmlSchema GetSchema()
        {
            return null;
        }
        #endregion

        #region ReadXml
        public void ReadXml(System.Xml.XmlReader xmlReader)
        {
            xmlReader.MoveToContent();
            this.timeStamp = DateTime.Parse(xmlReader.GetAttribute("timeStamp"));
            if (xmlReader.IsEmptyElement) return;
            xmlReader.ReadStartElement();
            if (xmlReader.Name == "dAgency") { xmlReader.ReadStartElement("dAgency"); this.Agency = new XmlSerializer(typeof(Agency)).Deserialize(xmlReader) as Agency; xmlReader.ReadEndElement(); }
            xmlReader.ReadEndElement();
        }
        #endregion

        #region WriteXml
        public void WriteXml(System.Xml.XmlWriter xmlWriter)
        {
            if (this.timeStamp.HasValue) xmlWriter.WriteAttributeString("timeStamp", this.timeStamp.Value.ToString("o"));
            if (this.Agency != null) { xmlWriter.WriteStartElement("dAgency"); new XmlSerializer(typeof(Agency)); xmlWriter.WriteEndElement(); }
        }
        #endregion
    }

    [Serializable]
    /// <summary></summary>
    [XmlType(Namespace = "http://www.nemsis.org")]
    [XmlRoot(Namespace = "http://www.nemsis.org", IsNullable = true)]
    public partial class Agency
    {
        #region EMSAgencyUniqueStateID
        private string _emsAgencyUniqueStateID;

        /// <summary>The unique ID assigned to the EMS Agency which is associated with all state licensure numbers and information.</summary>
        [XmlElement("dAgency.01")]
        public string EMSAgencyUniqueStateID
        {
            get
            {
                return this._emsAgencyUniqueStateID;
            }
            set
            {
                this._emsAgencyUniqueStateID = value;
            }
        }
        #endregion
    }
}

1 个答案:

答案 0 :(得分:0)

如何使用Linq To Xml

var xml = @"<DEMDataSet xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xsi:schemaLocation=""http://www.nemsis.org http://nemsis.org/media/XSD_v3/_nemsis_v3.3.1/3.3.1.130201/XSDs/NEMSIS_XSDs_v3.3.1.130201/DEMDataSet_v3.xsd""  xmlns=""http://www.nemsis.org"">
                <DemographicReport timeStamp=""1969-03-14T07:38:20+07:00"">
                    <dAgency>
                        <dAgency.01>M</dAgency.01>
                    </dAgency>
                </DemographicReport>
            </DEMDataSet>";

var xDoc = XDocument.Parse(xml);
XNamespace ns = "http://www.nemsis.org";
var result = xDoc.Descendants(ns + "DemographicReport")
                .Select(d => new DemographicReportGroup
                {
                    timeStamp = (DateTime)d.Attribute("timeStamp"),
                    Agency = new Agency{EMSAgencyUniqueStateID = d.Descendants(ns + "dAgency.01").First().Value}
                })
                .ToList();

public class DemographicReportGroup
{
    public Agency Agency { set; get; }
    public DateTime timeStamp;
}

public class Agency
{
    public string EMSAgencyUniqueStateID { set; get; }
}