Append new xmlNode to multiple xmlnodes using xmlnodeslist just keeps the last change?

89 views Asked by At

I am trying to append an xmlNode in different places of xmlDocument. Here is the simplified version of my xml file:

<?xml version="1.0" encoding="UTF-16"?>
<Campus id="cmps-1">
    <Location>
        <Name>Boston, IN, USA</Name>
    </Location>
    <Building id="bldg-1" buildingType="TownHall">
        <Area>1928.368051</Area>
        <Name>Level 1</Name>
        <Space id="sp-1" IdRef="bldg-stry-1">
            <Name>5 BEDROOM 1</Name>
        </Space>
        <Space id="sp-2" IdRef="bldg-stry-1">
            <Name>5 BEDROOM 1</Name>
        </Space>
        <Space id="sp-3" IdRef="bldg-stry-1">
            <Name>5 BEDROOM 1</Name>
        </Space>        
    </Building>
</Campus>

I want to add the following xmlNode to "Space" node after "Name" element.

<Inf>
    <Blow />
</Inf>

Here is the code I am using:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"C:\mm.xml");

XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("mm", "http://www.mm.com");

XmlNodeList spaceNodes = xmlDoc.SelectNodes("descendant::mm:Space");

//node to be added
XmlNode infNode = xmlDoc.CreateNode(XmlNodeType.Element, "Inf", "http://www.mm.com");
XmlNode blowNode = xmlDoc.CreateNode(XmlNodeType.Element, "Blow", "http://www.mm.com");
infNode.AppendChild(blowNode);

foreach (XmlNode spaceN in spaceNodes)
{
    spaceN.AppendChild(infNode);
}
xmlDoc.Save(@"C:\mmNew.xml");

But the code saves it just for one "Space" node and looses the previous one that was created in the loop. So at the end only the last space has the node added. I have read a few similar posts (tried for loop instead foreach and used system list rather too), but could not solve this problem. I would appreciate if you can help me.

1

There are 1 answers

0
mrah On BEST ANSWER

I got the solution. I just need to define the parameters in the loop to solve the issue.