0

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

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

我正在努力实现 for 的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属性是日期/时间。如果它是一个 plain 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
    }
}
4

1 回答 1

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; }
}
于 2013-04-16T17:27:02.947 回答