我正在创建一个XDocument
,里面填充了一组数据。
输出如下所示:
<Results>
<RuleResult>
<Title> RuleTitle </Title>
</RuleResult>
<RuleResult>
<Title> Rule2Title </Title>
</RuleResult>
</Results>
现在我如何在 C# 中制定如下:
XDocument doc = new XDocument(new XElement("Results"));
foreach (AnalysisSet rules in allAnalysisSets)
{
foreach (var rule in rules.Rules)
{
doc.Root.Add(new XElement(rule.GetRuleState()));
}
}
据我了解,这会创建"Results"
作为根级节点。
我的问题是,如果我想设置它以便封装上述所有内容<AnalysisSets>
那么它将是:
<AnalaysisSets>
<AnalysisSet ProviderName="ProductNameHere">
<Results>
<....xml data..../>
</Results>
</AnalysisSet>
</AnalysisSets>
我该怎么做? 似乎我会尝试创建一个根元素,然后创建 2 个子根元素? 我不太确定如何做到这一点,如果这确实是正确的起点。
您是否考虑过仅使用直接序列化?无论如何,这是我的完整模型。
编辑:我忘记了结果节点:-)
public class Program
{
private static void Main(string[] args)
{
var allAnalysisSets = new AnalysisSet[] {
new AnalysisSet(){
ProviderName = "productname1",
Rules = new Rule[]{
new Rule(){ Title="rule1" }
} },
new AnalysisSet(){
ProviderName = "productname2",
Rules = new Rule[]{
new Rule(){ Title="rule1" },
new Rule(){ Title="rule2" }
} }
};
var sb = new StringBuilder();
using (var sw = new StringWriter(sb))
using (var xw = XmlWriter.Create(sw, new XmlWriterSettings() { Indent = true }))
{
new XElement("AnalaysisSets"
, allAnalysisSets
.Select(set => new XElement("AnalysisSet"
, new XAttribute("ProviderName", set.ProviderName)
, new XElement("Results"
, set.Rules.Select(rule => rule.GetRuleState())
)
)
)
).WriteTo(xw);
}
Console.Write(sb.ToString());
Console.ReadLine();
}
}
public class AnalysisSet
{
public IEnumerable<Rule> Rules { get; set; }
public string ProviderName { get; set; }
}
public class Rule
{
public string Title { get; set; }
public XStreamingElement GetRuleState()
{
return new XStreamingElement("RuleResult",
new XElement("Title", Title));
}
}