RobertC
RobertC

Reputation: 123

XDocument formatting elements

I have an issue with xdocument I keep getting this format:

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

Here is my code:

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

However I need the output to be in the following format:

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

----Edit

I have also tried:

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

The above didn't work either.

Upvotes: 1

Views: 88

Answers (1)

B.K.
B.K.

Reputation: 10162

Let's format your code to see what's happening:

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

You are creating the second 'RULE' element within the first one. So, you have root element 'DB', which has a 'RULE' child, which has a 'RULE' child.

Try this instead:

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

Code readability goes a long way in solving bugs.

Upvotes: 1

Related Questions