insert string into specific place in xml

I have an xml like below and in my script I want to replace each <area with an array of xml strings.

So I would loop through each array for each area name and would like to insert the xml string one after another then remove the area name section.

What's the best way of doing this?

<root>
      <node>
            <node>
                  <area name="30"/>
            </node>
      </node>
      
      <node>      
            <area name="20"/>
      </node>
      
      <area name="10"/>
</root>
NewtonianBAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

nativCommented:
I'm not sure how you are matching your area nodes with the arrays. I would assume it is based on the name in the area node.
It might be a simple matter of replacing a string.
Store the XML in a string. (MainXML)
For each area, concatenate all the XML strings in the array and then simply do a replace:
MainXML = MainXML.Replace("<area name=""30""/>", string.Concat(XMLArray30));

You can either hardcode each area or loop though the different arrays depending on how you name your arrays.
anarki_jimbelSenior DeveloperCommented:
can you show an example of what 's to be achieved? It's not clear from the question above
NewtonianBAuthor Commented:
arrayNameThirty = ["<somexml>", "<morexml>"]
arrayNameTwenty = ["<somexml2>", "<morexml2>"]
arrayNameTen = ["<somexml3>", "<morexml3>"]

<root>
      <node>
            <node>
                 <somexml>
                 <morexml>
            </node>
      </node>
     
      <node>      
                 <somexml2>
                 <morexm2l>
      </node>
     
                 <somexml3>
                 <morexml3>
</root>
Become a Certified Penetration Testing Engineer

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

nativCommented:
This still looks like the simplest route.
MainXML = MainXML.Replace("<area name=""30""/>", string.Concat(arrayNameThirty));
MainXML = MainXML.Replace("<area name=""20""/>", string.Concat(arrayNameTwenty));
MainXML = MainXML.Replace("<area name=""10""/>", string.Concat(arrayNameTen));
nativCommented:
On the other hand, String manipulation of XML documents is not best practice.
In which case you could use XPathNavigator
Something to this effect:

XPathDocument doc = new XPathDocument(@"C:\test.xml");
XPathNavigator root = doc.CreateNavigator();
XPathNodeIterator nodes = root.Select("//area");
while (nodes.MoveNext())
{  
     nodes.Current.DeleteSelf();
switch (nodes.Current.GetAttribute("name", "")){
   case "10":
     foreach(string s in ArrayNameTen){
	 nodes.MoveParent.AppendChild(s);
     }
     break;
 case "20":
     foreach(string s in ArrayNameTwenty){
	 nodes.MoveParent.AppendChild(s);
     }
     break;
 case "30":
     foreach(string s in ArrayNameThirty){
	 nodes.MoveParent.AppendChild(s);
     }
     break;
   }
}

Open in new window

anarki_jimbelSenior DeveloperCommented:
Hmmm,

this is not well-formed xml, in the first place - no closing tags for new elements

Should it be like below?

<root>
      <node>
            <node>
                 <somexml/>
                 <morexml/>
            </node>
      </node>
      
      <node>      
                 <somexml2/>
                 <morexm2l/>
      </node>
      
                 <somexml3/>
                 <morexml3/>
</root>

Open in new window

anarki_jimbelSenior DeveloperCommented:
OK, I've written a program, it's not really complex. Just keep in mind we may get a collection of nodes to replace but we cannot delete nodes while iterating the collection. That's why I use a dictionary. If you have questions - ask.

The output from the file:

<root>
  <node>
    <node>
      <somexml />
      <morexml />
    </node>
  </node>
  <node>
    <somexml2 />
    <morexml2 />
  </node>
  <somexml3 />
  <morexml3 />
</root>
        private void button3_Click(object sender, EventArgs e)
        {
            string[] arrayNameThirty = {"<somexml>", "<morexml>"};
            string[] arrayNameTwenty = {"<somexml2>", "<morexml2>"};
            string[] arrayNameTen = { "<somexml3>", "<morexml3>" };
            
            XmlDocument doc = new XmlDocument();
            doc.Load("XMLFile1.xml");
            XmlNodeList nodes = doc.GetElementsByTagName("area");

            Dictionary<XmlNode, XmlNode> parent_child = new Dictionary<XmlNode, XmlNode>();
            foreach (XmlNode node in nodes)
            {
                if (node.Attributes["name"].Value == "10")
                {
                    ReplaceNodes(doc, node, arrayNameTen, parent_child);
                }
                else if (node.Attributes["name"].Value == "20")
                {
                    ReplaceNodes(doc, node, arrayNameTwenty, parent_child);
                }
                else if (node.Attributes["name"].Value == "30")
                {
                    ReplaceNodes(doc, node, arrayNameThirty, parent_child);
                }

            }
            foreach (XmlNode parent in parent_child.Keys)
            {
                parent.RemoveChild(parent_child[parent]);
            }
            doc.Save("NewXml");
            MessageBox.Show("Done");
        }

        private void ReplaceNodes(XmlDocument doc, XmlNode node, string[] namesForReplacement, Dictionary<XmlNode, XmlNode> parent_child)
        {
            char[] trimParams = { '<', '>' };
            XmlNode parent = node.ParentNode;
            foreach (string s in namesForReplacement)
            {
                XmlNode newChild = doc.CreateElement(s.Trim(trimParams));
                parent.AppendChild(newChild);
            }
            //We can't remove nodes now!
            parent_child.Add(parent, node);
        }

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
NewtonianBAuthor Commented:
amazing guys thanks alot
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
XML

From novice to tech pro — start learning today.