views:

211

answers:

3

How do i write something in the innertext of my xml file

i am able to read the particualar tag from the file like this:

 protected void Page_Load(object sender, EventArgs e)
    {// this is to read from xml.
        if (!Page.IsPostBack)
        {
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.Load(@"C:\configfolder\config.xml");

            XmlNodeList portNo = xmlDoc.GetElementsByTagName("AgentConfigRepository");
            foreach (XmlNode node in portNo)
            {
                XmlElement bookElement = (XmlElement)node;
                string no = bookElement.GetElementsByTagName("OVERRIDE_CONFIG_FILE_NAME")[0].InnerText;
                TextBox1.Text = no;
            }
        }
    }

Now i want to change the value in the innertext of OVERRIDE_CONFIG_FILE_NAME

this is how my xml file looks like:

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<AgentConfigRepository>
  <SERVER_SHARE_SW_DIR_NAME val="singleVal">AgentSW</SERVER_SHARE_SW_DIR_NAME>
  <OVERRIDE_CONFIG_FILE_NAME val="singleVal">override_config.xml</OVERRIDE_CONFIG_FILE_NAME>
  <MAINTAIN_AGENT_SW_LEVEL val="singleVal">1.0</MAINTAIN_AGENT_SW_LEVEL>
  <MAINTAIN_AGENT_SW_PATCH_LEVEL val="singleVal">0</MAINTAIN_AGENT_SW_PATCH_LEVEL>
</AgentConfigRepository>

so i want to change override_config.xml to some other value in the textbox.

any suggestions.. thanks

+1  A: 

If you can use XDocument, it becomes pretty trivial:

XDocument xdoc = XDocument.Load(@"C:\configfolder\config.xml");
xdoc.Root.Element("OVERRIDE_CONFIG_FILE_NAME").SetValue("HelloThere");
xdoc.Save(@"C:\so2.xml");
RandomNoob
A: 

Unfortunately this is untested at the moment (I am not in a location to test it) but from the looks of your question you are trying to change the innerText of the Element you have found in this line:

bookElement.GetElementsByTagName("OVERRIDE_CONFIG_FILE_NAME")[0].InnerText;

To whatever is in your text box. Generally you want a statement like this:

bookElement.GetElementsByTagName("OVERRIDE_CONFIG_FILE_NAME")[0].InnerText = "new text"

New Text can be the string from a text box in your app or another variable or just hardcoded (as in this example). Hope this helps.

Tim C
i had tried this before but it did not work alone like this... thanks though
A: 

You can just set the InnerText like any other property (As Tim C said)

When you do this, however, it only sets it in the XmlDocument object. In order to see the change in the file, you have to do save the changes back to the file:

bookElement.save(filename)

Adam