XDocument格式化元素

时间:2016-01-29 06:03:31

标签: c# .net

我有xdocument的问题我一直都是这样的格式:

<DB caption="001" rules="6">
    <RULES>
        <RULE data_type="2" option="0">
            <RULE data_type="2" option="0"/>
        </RULE>
    </RULE>
</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 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"));

上述情况也不起作用。

1 个答案:

答案 0 :(得分:1)

让我们对您的代码进行格式化,以了解发生了什么:

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")));

您正在创建第二个“规则”&#39;第一个元素。所以,你有根元素&#39; DB&#39;它有一个&#39;规则&#39;孩子,有一个&#39; RULE&#39;子。

请改为尝试:

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")));

代码可读性在解决错误方面有很长的路要走。