XMLSerializer 异常"There was an error reflecting field"和"For non-array types, you may use the followin



我是新手,请耐心等待。我需要将JSON字符串转换为XML进行一些修改从

{"computerid":123456,"computername":"mycomputer","computermodel":"mymodel"}

<?xml version="1.0"?>
<SqlMultiFilter xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Parameter>
<Filter>
<ParamName>computerid</ParamName>
<ParamValues>
<ParamValue>123456</ParamValue>
</ParamValues>
</Filter>
<Filter>
<ParamName>computername</ParamName>
<ParamValues>
<ParamValue>mycomputer</ParamValue>
</ParamValues>
</Filter>
<Filter>
<ParamName>computermodel</ParamName>
<ParamValues>
<ParamValue>mymodel</ParamValue>
</ParamValues>
</Filter>
</Parameter>
</SqlMultiFilter>

我用这种方式创建了一个公共类

[XmlRoot("SQLMultiFilter", Namespace = "http://www.cpandl.com",
IsNullable = false)]
public class SQLMultiFilter
{
[XmlArrayAttribute("Parameter")]
public string ParamName;
[XmlArrayAttribute("ParamValues")]
public string ParamValue;
}

当我张贴我的json,我得到错误在这个

XmlSerializer serializer = new XmlSerializer(typeof(SQLMultiFilter));

错误
Inner Exception 1:
InvalidOperationException: There was an error reflecting field 'ParamName'.
Inner Exception 2:
InvalidOperationException: For non-array types, you may use the following attributes: XmlAttribute, XmlText, XmlElement, or XmlAnyElement.

我哪里错了?

Thanks in advance

[XmlRoot("SQLMultiFilter", Namespace = "http://www.cpandl.com", IsNullable = false)]
public class SqlMultiFilter
{
public List<Filter> Parameter { get; set; }
}
public class Filter
{
public string ParamName;
[XmlArrayItem("ParamValue")]
public List<string> ParamValues { get; set; }
}

这两个类将允许您再现所示模式的XML。

var serializer = new XmlSerializer(typeof(SqlMultiFilter));
var sqlMultiFilter = new SqlMultiFilter
{
Parameter = new List<Filter>
{
new Filter { ParamName = "computerid", ParamValues = new List<string> { "123456" } },
new Filter { ParamName = "computername", ParamValues = new List<string> { "mycomputer" } },
new Filter { ParamName = "computermodel", ParamValues = new List<string> { "mymodel" } }
}
};
var settings = new XmlWriterSettings { Indent = true };
using (var xmlWriter = XmlWriter.Create(Console.Out, settings))
serializer.Serialize(xmlWriter, sqlMultiFilter);

将给出期望的结果。

相关内容