Please be patient because I'm a newbie. I need to transform a JSON string to an XML making some modifications From
{"computerid":123456,"computername":"mycomputer","computermodel":"mymodel"}
To
<?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>
I created a public class in that way
[XmlRoot("SQLMultiFilter", Namespace = "http://www.cpandl.com",
IsNullable = false)]
public class SQLMultiFilter
{
[XmlArrayAttribute("Parameter")]
public string ParamName;
[XmlArrayAttribute("ParamValues")]
public string ParamValue;
}
When I post my json I got errors in this
XmlSerializer serializer = new XmlSerializer(typeof(SQLMultiFilter));
Errors
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.
Where I go wrong?
Thanks in advance
CodePudding user response:
[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; }
}
These two classes will allow you to reproduce the XML of the schema shown.
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);
Will give the desired result.