C# XDocument格式化元素

C# XDocument格式化元素,c#,.net,C#,.net,我对xdocument有问题,我一直使用这种格式: <DB caption="001" rules="6"> <RULES> <RULE data_type="2" option="0"> <RULE data_type="2" option="0"/> </RULE> </RULE> </DB> 但是,我需要输出为以下格式: <DB

我对xdocument有问题,我一直使用这种格式:

<DB caption="001" rules="6">
    <RULES>
        <RULE data_type="2" option="0">
            <RULE data_type="2" option="0"/>
        </RULE>
    </RULE>
</DB>
但是,我需要输出为以下格式:

<DB caption="001" rules="6">
    <RULES>
        <RULE data_type="2" option="0"/>
        <RULE data_type="2" option="0"/>
    </RULES>
</DB>

上述操作也不起作用。

让我们格式化您的代码,看看发生了什么:

new XElement("DB",
    new XAttribute("caption", "001"),
    new XAttribute("rules","6"),
    new XElement("RULE",
        new XAttribute("data_type", "2"),
        new XAttribute("option", "0"),
        new XElement("RULE",
            new XAttribute("data_types", "2"),
            new XAttribute("option", "0")));
您正在第一个“规则”元素中创建第二个“规则”元素。因此,您有根元素“DB”,它有一个“RULE”子元素,它有一个“RULE”子元素

请尝试以下方法:

new XElement("DB",
    new XAttribute("caption", "001"),
    new XAttribute("rules","6"),
    new XElement("RULE",
        new XAttribute("data_type", "2"),
        new XAttribute("option", "0")),
    new XElement("RULE",
        new XAttribute("data_type", "2"),
        new XAttribute("option", "0")));

代码可读性在解决bug方面有很大帮助。

只要仔细查看右括号,就会发现您在第一个规则元素中创建了第二个规则元素。。您好,我也尝试过在“RULE”处关闭括号,但格式仍然不正确。@RobertC没问题。
new XElement("DB",
    new XAttribute("caption", "001"),
    new XAttribute("rules","6"),
    new XElement("RULE",
        new XAttribute("data_type", "2"),
        new XAttribute("option", "0"),
        new XElement("RULE",
            new XAttribute("data_types", "2"),
            new XAttribute("option", "0")));
new XElement("DB",
    new XAttribute("caption", "001"),
    new XAttribute("rules","6"),
    new XElement("RULE",
        new XAttribute("data_type", "2"),
        new XAttribute("option", "0")),
    new XElement("RULE",
        new XAttribute("data_type", "2"),
        new XAttribute("option", "0")));