Devester
Devester

Reputation: 1183

How to add a parent node using foreach

I have got a big trouble in my Xml generator using C#. I could not find how to add a parent node containing the element's name.

The information is coming from a database and inserted into the Xml document in memory. I have to get those nodes by name because I will need to convert some of them.

Code:

XmlElement xe = xd.CreateElement("xe");

foreach (XmlNode node in xd.DocumentElement.ChildNodes)
{
    XmlNode imported = xd.ImportNode(node, true);
    xe.AppendChild(imported["a"]);
    xe.AppendChild(imported["b"]);
    xe.AppendChild(imported["c"]);
    xe.AppendChild(imported["d"]);
}

Result:

<node>
    <a>1</a>
    <b>2</b>
    <c>3</c>
    <d>4</d>
    <a>1</a>
    <b>2</b>
    <c>3</c>
    <d>4</d>
    <a>1</a>
    <b>2</b>
    <c>3</c>
    <d>4</d>
</node>

What I need:

<node>
    <ex>
        <a>1</a>
        <b>2</b>
        <c>3</c>
        <d>4</d>
    </ex>
    <ex>
        <a>1</a>
        <b>2</b>
        <c>3</c>
        <d>4</d>
    </ex>
    <ex>
        <a>1</a>
        <b>2</b>
        <c>3</c>
        <d>4</d>
    </ex>
</node>

Upvotes: 1

Views: 1883

Answers (2)

Aghilas Yakoub
Aghilas Yakoub

Reputation: 28980

You can use this code

    XmlElement xe = xd.CreateElement("xe");

    foreach (XmlNode node in xd.DocumentElement.ChildNodes)
    {
        XmlNode imported = xd.ImportNode(node, true);

        XmlElement child = xd.CreateElement("ex");

        child.AppendChild(imported["a"]);
        child.AppendChild(imported["b"]);
        child.AppendChild(imported["c"]);
        child.AppendChild(imported["d"]);

        xe.AppendChild(child); 

    }

Upvotes: 1

Louis Kottmann
Louis Kottmann

Reputation: 16628

Append the children to an element named "ex", then append that element to the root

    foreach (XmlNode node in xd.DocumentElement.ChildNodes)
    {
        XmlNode imported = xd.ImportNode(node, true);
        XmlElement ex = xd.CreateElement("ex");
        ex.AppendChild(imported["a"]);
        ex.AppendChild(imported["b"]);
        ex.AppendChild(imported["c"]);
        ex.AppendChild(imported["d"]);
        xd.AppendChild(ex);
    }

Upvotes: 3

Related Questions