Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize name value pair array without enclosing node using XmlSerializer

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.

like image 718
sjlewis Avatar asked Feb 22 '23 04:02

sjlewis


1 Answers

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>
like image 170
SwDevMan81 Avatar answered Apr 26 '23 13:04

SwDevMan81