序列化名称值对数组,而不使用XmlSerializer封闭节点

时间:2011-12-08 16:08:16

标签: c# xml-serialization

我有这门课......

[XmlRoot("config")]
public class SourceConfig
{
    public string Description { get; set; }

    public string HelpLink { get; set; }
}

...我将其序列化为...

<config>
  <Description />
  <HelpLink />
  <param name="param1" value="" />
  <param name="param2" value="" />
</config>

...使用XmlSerializer +使用XmlDocument的后处理添加<param>元素。

有没有更好的方法来序列化<param>元素而不使用XmlDocument进行后期处理?

我尝试使用XmlArray属性,但<param>元素最终在另一个节点内。

1 个答案:

答案 0 :(得分:8)

将其设为XmlElement:

[XmlRoot("config")]
public class SourceConfig
{
    public string Description { get; set; }

    public string HelpLink { get; set; }

    [XmlElement("param")]
    public List<Params> param { get; set; }
}

完整的工作示例:

[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);
   }
}

输出以下内容:

<?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>