【问题标题】:How resolve the issues in deserializing the xml returned by a rest service?如何解决rest服务返回的xml反序列化问题?
【发布时间】:2014-01-17 13:14:59
【问题描述】:

当我尝试反序列化来自 web 客户端的 rest 服务响应的 xml 时,出现以下错误。

{System.InvalidOperationException: XML 文档中存在错误 (1, 2)。 ---> System.InvalidOperationException: 不是 预期的。在 Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderRoot.Read6_Root() --- 内部异常堆栈跟踪结束 --- 在 System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader、字符串 encodingStyle、对象事件)在 System.Xml.Serialization.XmlSerializer.Deserialize(流流)
在 XmlParser.MainPage.DeserializeXmlData(Stream 流) 在 XmlParser.MainPage.c_DisplayClass6.b_5(Object s, OpenReadCompletedEventArgs e) 在 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;
        }

【问题讨论】:

  • 向我们展示您用于反序列化该 xml 的代码
  • @Alberto 我已经添加了代码。请找到我的编辑。

标签: c# xml deserialization


【解决方案1】:

元素的名称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 类并让您通过那个班到XmlSerializer)

【讨论】:

  • @damien-the-unbeliever 谢谢,但现在我收到了An exception of type 'System.InvalidOperationException' occurred in System.Xml.Serialization.ni.dll but was not handled in user 帮助我解决这个问题。
【解决方案2】:

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

如果有必要,则需要将其包装在信封中,并在信封元素中使用xmlns:n0="http:somenamespace" 属性。

【讨论】:

  • 我不同意。来自Namespaces in XML:“命名空间前缀,除非它是 xml 或 xmlns,必须已在使用前缀的元素的开始标记或祖先元素中的命名空间声明属性中声明”
  • 你是对的。我对提供的 xml 和代码做了更多的尝试,天哪,天哪,c# 出于某种原因不喜欢那个 xml。
【解决方案3】:

此问题是由于 REST 服务返回的 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() : "";
            }
        }
    }

【讨论】:

    猜你喜欢
    • 2023-03-11
    • 2014-03-23
    • 2019-11-21
    • 1970-01-01
    • 2019-02-12
    • 1970-01-01
    • 2011-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多