gpt4 book ai didi

c# - 无法反序列化 XML 字符串

转载 作者:数据小太阳 更新时间:2023-10-29 02:21:38 25 4
gpt4 key购买 nike

我有以下 xml,我试图按如下方式反序列化,但出现错误:

There was an error reflecting type 'System.Collections.Generic.List`1[MyApp.Models.Field]

下面是我的代码

public class FieldList
{
[XmlArray("fields")]
[XmlArrayItem("field")]
List<Field> Fields { get; set; }
}

public class Field
{
[XmlAttribute("type")]
public string Type { get; set; }

[XmlAttribute("required")]
public bool Required { get; set; }

[XmlAttribute("label")]
public string Label { get; set; }

[XmlAttribute("name")]
public string Name { get; set; }

[XmlElement("option")]
[JsonProperty("values")]
public List<Option> Options { get; set; }
}

public class Option
{
[XmlAttribute("label")]
public string Label { get; set; }

[XmlAttribute("value")]
public string Value { get; set; }

[XmlAttribute("selected")]
public bool Selected { get; set; }

/// <remarks/>
[XmlIgnore()]
public bool SelectedSpecified { get; set; }

[XmlText]
public string Text { get; set; }
}

var xml = @"<?xml version=""1.0"" ?>
<form-template>
<fields>
<field type=""select"" required=""true"" label=""Cars"" name=""cars"" >
<option label=""Toyota"" value=""Toyota"" selected=""true"">Toyota</option>
<option label=""Nisan"" value=""Nisan"" >Nisan</option>
</field>
</fields>
</form-template>";


var serializer = new XmlSerializer(typeof(FieldList), new XmlRootAttribute("form-template"));
var stringReader = new StringReader(xml);
var xmlFields = (FieldList)serializer.Deserialize(stringReader);

我做错了什么?

* 更新 *

根据下面的评论更改

 public IEnumerable<Option> Options { get; set; }

  public List<Option> Options { get; set; }

修复了错误,但现在没有反序列化 - 变量 xmlFields 为空???我需要从特定节点读取还是应该无关紧要?

最佳答案

XmlSerializer 无法序列化抽象属性,因此请将 IEnumerable 更改为 List,如下所示,

public IEnumerable<Option> Options { get; set; }

public List<Option> Options { get; set; }

您的根元素与您拥有的 XML 结构不匹配。我已经像下面这样编辑了 XML,

var xml = "<?xml version=\"1.0\" ?>" +
" " +
" <Fields>" +
" <Field Type=\"select\" Required=\"true\" Label=\"Cars\" Name=\"cars\" >" +
" <option label=\"Toyota\" lalue=\"Toyota\" selected=\"true\">Toyota</option>" +
" <option label=\"Nisan\" value=\"Nisan\" >Nisan</option>" +
" </Field>" +
" </Fields>";

并将代码反序列化为,

XmlSerializer serializer = new XmlSerializer(typeof(List<Field>), new XmlRootAttribute("Fields"));

var stringReader = new StringReader(xml);
List<Field> xmlFields = (List<Field>)serializer.Deserialize(stringReader);

现在可以反序列化了。请查看输出,

enter image description here

关于c# - 无法反序列化 XML 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46787748/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com