简体   繁体   English

XmlSerializer和将XML粘贴为类

[英]XmlSerializer & Paste XML as classes

I have a web service that is returning some xml. 我有一个返回一些xml的Web服务。 There is no corresponding xsd. 没有相应的xsd。

I used the Paste Special -> Paste XML as classes functionality in visual studio to generate the classes to use with XmlSerializer : 我在Visual Studio中使用选择性粘贴->粘贴XML作为类功能来生成要与XmlSerializer一起使用的类:

When the code executes the line 当代码执行该行时

--> XmlSerializer xmlSerialize = new XmlSerializer(typeof(table)); <--
    table t = (table)xmlSerialize.Deserialize(new StringReader(soapResult));

it throws an exception: 它抛出一个异常:

System.InvalidOperationException: 'Unable to generate a temporary class (result=1).
error CS0030: Cannot convert type 'string[]' to 'string'
error CS0029: Cannot implicitly convert type 'string' to 'string[]'

The generated classes look like so: 生成的类如下所示:

// NOTE: Generated code may require at least .NET Framework 4.5 or .NET Core/Standard 2.0.
    /// <remarks/>
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
    public partial class table
    {

        private string[] labelField;

        private string[] classnameField;

        private string[] datatypeField;

        private string[][] rowField;


        /// <remarks/>
        [System.Xml.Serialization.XmlArrayItemAttribute("d", IsNullable = false)]
        public string[] label
        {
            get
            {
                return this.labelField;
            }
            set
            {
                this.labelField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlArrayItemAttribute("d", IsNullable = false)]
        public string[] classname
        {
            get
            {
                return this.classnameField;
            }
            set
            {
                this.classnameField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlArrayItemAttribute("d", IsNullable = false)]
        public string[] datatype
        {
            get
            {
                return this.datatypeField;
            }
            set
            {
                this.datatypeField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlArrayItemAttribute("d", typeof(string), IsNullable = true)]
        public string[][] row
        {
            get
            {
                return this.rowField;
            }
            set
            {
                this.rowField = value;
            }
        }
    }

The problem is with the row field, as the others work ok. 问题出在行字段,其他的都可以。 If I change 如果我改变

[System.Xml.Serialization.XmlArrayItemAttribute("d", typeof(string), IsNullable = true)]

to

[System.Xml.Serialization.XmlArrayItemAttribute("d", typeof(string[]), IsNullable = true)]

the error goes away, but my object just has an array of empty string arrays. 错误消失了,但是我的对象只有一个空字符串数组。

The XML data being deserialized (condensed for simplicity) looks like this 反序列化的XML数据(为简单起见压缩)如下所示

<?xml version="1.0" encoding="UTF-8"?>
<table>
   <label>
      <d>JobDefinition.SearchName</d>
      <d>Job.JobDefinition</d>
   </label>
   <classname>
      <d>JobDefinition.SearchName</d>
      <d>Job.JobDefinition</d>
   </classname>
   <datatype>
      <d>String</d>
      <d>obj.JobDefinition</d>
   </datatype>
   <row>
      <d>AB_DEFG_QA_RUN</d>
      <d>A_JOB_Run</d>
   </row>
   <row>
      <d>AB_DEFG_QA_RUN</d>
      <d>B_JOB_Run</d>
   </row>
</table>

Your problem looks identical to the one described in the Final Update of this answer to How to serialize List<List<object>> ? 您的问题看起来与此答案最终更新中描述的问题相同, 该答案如何序列化List<List<object>> , namely that xsd.exe (and thus Paste XML as Classes ) is having trouble inferring a correct data model for XML containing a repeating element that contains nested repeating elements, here <row> and <d> : ,即xsd.exe (以及因此将XML粘贴为 xsd.exe )在为包含重复元素的XML推断正确的XML数据模型时遇到麻烦,其中重复元素包含嵌套的重复元素,此处为<row><d>

<table>
   <row>
      <d>Value of repeating element inside a repeating element.</d>
      <d>Value of repeating element inside a repeating element.</d>
   </row>
   <row>
      <d>Value of repeating element inside a repeating element.</d>
      <d>Value of repeating element inside a repeating element.</d>
   </row>
</table>

The recommendation in that answer is to use a different code generation tool or construct the classes manually. 该答案的建议是使用其他代码生成工具或手动构造类。 I uploaded your XML to https://xmltocsharp.azurewebsites.net/ and, after merging duplicate classes, obtained the following data model: 我将您的XML上传到https://xmltocsharp.azurewebsites.net/,并且在合并重复的类之后,获得了以下数据模型:

[XmlRoot(ElementName = "row")]
public class Row
{
    [XmlElement(ElementName = "d")]
    public List<string> D { get; set; }
}

[XmlRoot(ElementName = "table")]
public class Table
{
    [XmlElement(ElementName = "label")]
    public Row Label { get; set; }
    [XmlElement(ElementName = "classname")]
    public Row Classname { get; set; }
    [XmlElement(ElementName = "datatype")]
    public Row Datatype { get; set; }

    [XmlElement(ElementName = "row")]
    public List<Row> Row { get; set; }
}

Using this I am able to deserialize and re-serialize your XML successfully without data loss. 使用此工具,我可以成功地反序列化和重新序列化XML,而不会丢失数据。 Notes: 笔记:

  • The code-generation tool generated distinct yet identical classes for Label , Classname , Datatype and Row . 代码生成工具为LabelClassnameDatatypeRow生成了截然不同但相同的类。 I decided to merge them all into a single Row type, and use it for all the relevant members of Table . 我决定将它们全部合并为一个Row类型,并将其用于Table所有相关成员。

Sample fiddle here . 样品在这里摆弄。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM