我有这个班…
[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>
元素最终出现在另一个节点中。 最佳答案
将其设为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>