How to add a new XML node to file

Need to open an XML file and add a node? It is actually very simple

Here’s how:

Sample XML file:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <Page>
    <Id>1</Id>
    <Name>Default.aspx</Name>
    <Title>Client Management System </Title>
  </Page>
  <Page>
    <Id>2</Id>
    <Name>Login.aspx</Name>
    <Title>Login Page</Title>
   </Page>
  <Page>
 </configuration>

C#

     
            string SeoXmlFile = MapPath("SeoXml.xml");
            //create new instance of XmlDocument
            XmlDocument doc = new XmlDocument();
            //load from file
            doc.Load(SeoXmlFile);
            //create main node
            //create main node
            XmlNode node = doc.CreateNode(XmlNodeType.Element, "Page", null);


            //create the nodes first child
            XmlNode NodeId = doc.CreateElement("Id");
            NodeId.InnerText = "3";

            //create the nodes first child
            XmlNode NodeName = doc.CreateElement("Name");
            NodeName.InnerText = "Contact.aspx" ;
            //create the nodes second child
            XmlNode NodeTitle = doc.CreateElement("Title");
            //set the value
            NodeTitle.InnerText ="Contact Us Page Title";


            // add childes to father
            node.AppendChild(NodeId);
            node.AppendChild(NodeName);
            node.AppendChild(NodeTitle);


            // find the node we want to add the new node to
            doc.DocumentElement.AppendChild(node);
            // append the new node
          
            // save the file
            doc.Save(SeoXmlFile);
            LoadSeoGrid();

Now show what will be the new generated XML after Adding node

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <Page>
    <Id>1</Id>
    <Name>Default.aspx</Name>
    <Title>Client Management System </Title>
  </Page>
  <Page>
    <Id>2</Id>
    <Name>Login.aspx</Name>
    <Title>Login Page</Title>
   </Page>
  <Page>
  <Page>
    <Id>3</Id>
    <Name>Contact.aspxx</Name>
    <Title>Contact Us Page Title</Title>
   </Page>
  <Page>
 </configuration>

 

Related Posts

  • How to remove xml node using RemoveChild
  • How to remove xml elements using RemoveChild()?
  • Insert Html Tags Inside XML Node
  • Filling a Grid with Files in a Folder – C#
  • How to loop through all files in a folder using C#
I am Muhammod Arifur Rahman, CEO and founder of Learneveryday.net I worked on asp.net mainly. My second skill language is php and wordpress. I am also work on jquery. I love to work with new problem and feel happy when solve. www.smartdatasoft.com is my own company.

2 Comments on "How to add a new XML node to file"

  1. Bill West says:

    Where is the solution? Where is the code?
    Sort of a worthless website, isn’t it?

  2. thanks for your reply. It was happened for on new plugin. I fix that now you can read that. Thanks one again.

Got something to say? Go for it!

*