如何解决反序列化休息服务返回的xml的问题?

时间:2014-01-17 13:14:59

标签: c# xml deserialization

当我尝试从Web客户端反序列化xml的rest service respone时,我收到以下错误。

  

{System.InvalidOperationException:XML文档中存在错误   (1,2)。 ---> System.InvalidOperationException:不是   预期。在   Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderRoot.Read6_Root()   ---内部异常堆栈跟踪结束---在System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader)   xmlReader,String encodingStyle,Object events)at   System.Xml.Serialization.XmlSerializer.Deserialize(Stream stream)
  在XmlParser.MainPage.DeserializeXmlData(Stream stream)at   XmlParser.MainPage。<> c_ DisplayClass6.b _5(对象s,   OpenReadCompletedEventArgs e)at   System.Net.WebClient.OnOpenReadCompleted(OpenReadCompletedEventArgs e)   在System.Net.WebClient.OpenReadOperationCompleted(Object arg)}

服务返回的Xml是

<?xml version="1.0"?>
<ns0:Response xmlns:ns0="urn:ae:gov:testwebsite:uniqueness:genericcontentsrs:1">
    <GenericContents>
        <ModuleId>1296</ModuleId>
        <Title>Getting around</Title>
        <Description>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum., <a target="_blank" href="http://www.google.com">google.com</a>, provides useful information. People often rely on landmarks to give directions.<br /> <br />Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. gmk&rsquo;s Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</Description>
        <BuildingId>0</BuildingId>
        <GeoCoordinateX/>
        <GeoCoordinateY/>
    </GenericContents>
</ns0:Response>

我已经尝试过为该类添加XmlRoot属性,但它仍然会产生相同的错误。

在课程之后我习惯了反序列化xml

[XmlRoot(ElementName = "ns0:Response",)]
    public class Root
    {
        [XmlElement(ElementName = "ns0:Response")]
        public nsResponse _nsResponse { get; set; }  
    }

    public class nsResponse
    {
        [XmlElement(ElementName = "GenericContents")]
        public GenericContents _GenericContents { get; set; } 
    }

    public class GenericContents
    {
        [XmlElement(ElementName = "ModuleId")]
        public string _ModuleId { get; set; }

        [XmlElement(ElementName = "Title")]
        public string _Title { get; set; }

        [XmlElement(ElementName = "Description")]
        public string _Description { get; set; }

        [XmlElement(ElementName = "BuildingId")]
        public string _BuildingId { get; set; }

        [XmlElement(ElementName = "GeoCoordinateX")]
        public string _GeoCoordinateX { get; set; }

        [XmlElement(ElementName = "GeoCoordinateY")]
        public string _GeoCoordinateY { get; set; }
    }

这是我用于反序列化的代码

private Root DeserializeXmlData(System.IO.Stream stream)
        {
            XmlSerializer ser = new XmlSerializer(typeof(Root));
            Root result = (Root)ser.Deserialize(stream);
            return result;
        }

3 个答案:

答案 0 :(得分:2)

元素的名称Response,而不是ns0:Response。名称空间前缀不是正式名称的一部分。以下两个xml在信息上是相同的:

<a:b xmlns:a="urn:damiens_namespace"/>

<y:b xmlns:y="urn:damiens_namespace"/>

因此,当您在代码中声明它们时,重要的是命名空间,而不是前缀:

[XmlRoot(ElementName = "Response",
         Namespace="urn:ae:gov:testwebsite:uniqueness:genericcontentsrs:1")]
    public class Root
    {

(再看一下你的代码,我不确定Root课的目的是什么。我原本期望XmlRoot()适用于nsResponse class,并让您将该类传递给XmlSerializer

答案 1 :(得分:0)

ns0是xml文档中未声明的前缀,很可能导致您的错误。

如果有必要,则需要将其包裹在信封元素中带有xmlns:n0="http:somenamespace"属性的信封中。

答案 2 :(得分:0)

此问题是由于其余服务返回的Xml文件中的空节点值。在xml文件中,您有两个空节点值GeoCoordinateX和GeoCoordinateY。

通过更改反序列化类来解决问题。

[XmlRoot(ElementName = "ns0:Response",)]
    public class Root
    {
        [XmlElement(ElementName = "ns0:Response")]
        public nsResponse _nsResponse { get; set; }  
    }

    public class nsResponse
    {
        [XmlElement(ElementName = "GenericContents")]
        public GenericContents _GenericContents { get; set; } 
    }

    public class GenericContents
    {
        private string moduleIdField;

        private string titleField;

        private string descriptionField;

        private string buildingIdField;

        private string geoCoordinateXField;

        private string geoCoordinateYField;

        public string ModuleId
        {
            get
            {
                return (!string.IsNullOrEmpty(moduleIdField)) ? moduleIdField.ToString() : "";
            }
            set
            {
                this.moduleIdField = !string.IsNullOrEmpty(value) ? (value).ToString() : "";
            }
        }

        /// <remarks/>
        public string Title
        {
            get
            {
                return (!string.IsNullOrEmpty(titleField)) ? titleField.ToString() : "";
            }
            set
            {
                this.titleField = !string.IsNullOrEmpty(value) ? (value).ToString() : "";
            }
        }

        /// <remarks/>
        public string Description
        {
            get
            {
                return (!string.IsNullOrEmpty(descriptionField)) ? descriptionField.ToString() : "";
            }
            set
            {
                this.descriptionField = !string.IsNullOrEmpty(value) ? (value).ToString() : "";
            }
        }

        /// <remarks/>
        public string BuildingId
        {
            get
            {
                return (!string.IsNullOrEmpty(buildingIdField)) ? buildingIdField.ToString() : "";
            }
            set
            {
                this.buildingIdField = !string.IsNullOrEmpty(value) ? (value).ToString() : "";
            }
        }

        /// <remarks/>
        public string GeoCoordinateX
        {
            get
            {
                return (!string.IsNullOrEmpty(geoCoordinateXField)) ? geoCoordinateXField.ToString() : "";
            }
            set
            {
                this.geoCoordinateXField = !string.IsNullOrEmpty(value) ? (value).ToString() : "";
            }
        }

        /// <remarks/>
        public string GeoCoordinateY
        {
            get
            {
                return (!string.IsNullOrEmpty(geoCoordinateYField)) ? geoCoordinateYField.ToString() : "";
            }
            set
            {
                this.geoCoordinateYField = !string.IsNullOrEmpty(value) ? (value).ToString() : "";
            }
        }
    }