构建XDocument以正确格式化标记

时间:2012-12-06 15:46:32

标签: c# xml xml-serialization xml-formatting

我创建的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>

我该怎么做?好像我会尝试创建一个Root元素,然后是2个子根元素?我不太确定如何实现这一点,如果这确实是开始的正确轨道。

1 个答案:

答案 0 :(得分: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));
    }
}