I have this class...
[XmlRoot("config")]
public class SourceConfig
{
public string Description { get; set; }
public string HelpLink { get; set; }
}
...which I serialize into this...
<config>
<Description />
<HelpLink />
<param name="param1" value="" />
<param name="param2" value="" />
</config>
...using XmlSerializer
+ post-process using XmlDocument
to add the <param>
elements.
Is there a better way to serialize the <param>
elements without post-processing using XmlDocument
?
I tried using XmlArray
attribute but the <param>
elements ended up inside another node.
Make it an XmlElement:
[XmlRoot("config")]
public class SourceConfig
{
public string Description { get; set; }
public string HelpLink { get; set; }
[XmlElement("param")]
public List<Params> param { get; set; }
}
Complete working example:
[XmlRoot("config")]
public class SourceConfig
{
public SourceConfig() {
Description = String.Empty;
HelpLink = String.Empty;
Parameters = new List<ParamDetails>();
}
public string Description { get; set; }
public string HelpLink { get; set; }
[XmlElement("param")]
public List<ParamDetails> Parameters { get; set; }
}
public class ParamDetails {
[XmlAttribute("name")]
public string name;
[XmlAttribute("value")]
public string value;
}
static class Program {
static void Main() {
XmlSerializer ser1 = new XmlSerializer(typeof(SourceConfig));
SourceConfig list1 = new SourceConfig();
list1.Description = "Test Desc";
list1.HelpLink = String.Empty;
list1.Parameters.Add(new ParamDetails { name = "param1", value = "1" });
list1.Parameters.Add(new ParamDetails { name = "param2", value = "2" });
ser1.Serialize(Console.Out, list1);
}
}
Outputs the following:
<?xml version="1.0" encoding="IBM437"?>
<config
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Description>Test Desc</Description>
<HelpLink />
<param name="param1" value="1" />
<param name="param2" value="2" />
</config>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With