我有几个已经序列化为XML文件的列表。
我很难弄清楚如何在我的元素列表中放置一个XML包装元素。
目前我的XML看起来像这样:
<finding>
<issue1></issue1>
<issue2><issue2 />
<issue3><issue3 />
</finding>
<finding>
<issue1></issue1>
<issue2><issue2 />
<issue3><issue3 />
</finding>
我想包装这些finding
元素,以便XML看起来像这样:
<Findings>
<finding>
<issue1></issue1>
<issue2><issue2 />
<issue3><issue3 />
</finding>
<finding>
<issue1></issue1>
<issue2><issue2 />
<issue3><issue3 />
</finding>
<findings/>
以下是我如何序列化:
[XmlElement("finding")]
public List<Findings> Findings { get {return findings;}}
[XmlElement("Issue1")]
public string getIssue1 { get { return issue1; } }
[XmlElement("issue2")]
public string getissue2 { get { return issue2; } }
[XmlElement("issue3")]
public string getissue3 { get { return issue3; } }
这是调用代码:
XmlSerializer ser = new XmlSerializer(typeof(RuleSet));
using (StreamWriter writer = new StreamWriter(fileName))
{
ser.Serialize(writer, findings);
}
调查结果类:
[Serializable()]
[XmlRoot("Findings")]
public class Findings
{
public string issue1;
public string issue2;
public string issue3;
public string issue4;
public Findings()
{
}
public Findings(string string flag1, string flag2, string flag3, string flag4)
{
this.issue1 = flag1;
this.issue2 = flag2;
this.issue3 = flag3;
this.issue4 = flag4;
}
}
}
和规则集类
[Serializable()]
public class RuleSet
{
private List<Findings> findings = new List<Findings>();
Findings findresults = new Findings();
[XmlElement("finding")]
public List<Findings> Findings { get {return findings;}}
[XmlElement("Issue1")]
public string getIssue1 { get { return findresults.issue1; } }
[XmlElement("issue2")]
public string getissue2 { get { return findresults.issue2; } }
[XmlElement("issue3")]
public string getissue3 { get { return findresults.issue3; } }
[XmlElement("issue4")]
public string getissue4 { get { return findresults.issue4; } }
public void setFindings(List<Findings> findings)
{
this.findings = findings;
}
public void addFindings(Findings findings)
{
this.findings.Add(findings);
}
}
}
我一直在和它斗争几个小时。我错过了什么?
答案 0 :(得分:1)
这应该有效:
public class Findings
{
[System.Xml.Serialization.XmlElementAttribute("finding")]
public List<Finding> finding = new List<Finding>();
}
public class Finding
{
public string issue1;
public string issue2;
public string issue3;
}
请注意列出项目名称的XmlElementAttribute
。在这种情况下,小写finding
。另外,我的示例使用issue1
等字段,但您的属性会很好。