<%@ Import Namespace="System" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Xml" %>
<script language="c#" runat="server">
/*************
* On page load, I want to read the contents of the "config.web" file,
modify some elements and
* add some elements withing the "configuration" tag. It may not make
sense here but this was just
* a test before I include this within my app in case it doesn't work.
what I want to do here is add the element
* "appsettings" and add a sub-element of "appsettings" called "add"
whose attributes consist of "key" and "value".
*************/
public void Page_Load(Object obj, EventArgs evnt) {
string file_path = Server.MapPath("config.web");
StringWriter string_writer = new StringWriter();
// create xmldocument object
XmlDocument xml_document = new XmlDocument();
// load "config.web" file into my xmldocument object.
xml_document.Load(file_path);
// add the "appsettings" element.
xml_document.Root.AddElement("appsettings");
// It is from here that things do not happen as what I thought they
would. I try to add a sub
// element to "appsettings" but nothing appears when I print out the
XML.
XmlNodeWriter node_writer = new
XmlNodeWriter(xml_document.Root["appsettings"].Context);
// **first element with attributres**
// adding the element tag
node_writer.WriteStartTag("add");
// addingthe attributes
node_writer.WriteAttrString("key","machine1");
node_writer.WriteAttrString("value","192.168.1.107");
// adding end of element tag
node_writer.WriteEndTag();
// **second element with attributres**
node_writer.WriteStartTag("add");
// addingthe attributes
node_writer.WriteAttrString("key","machine2");
node_writer.WriteAttrString("value","192.168.1.108");
// adding end of element tag
node_writer.WriteEndTag();
// write the xmldocument to my string writer
xml_document.Save(string_writer);
// print out my xmldocument
Response.ContentType = "text/xml";
Response.Write(string_writer.ToString());
}
</script>
OUTPUT:
<?xml version="1.0" ?>
- <configuration>
- <httphandlers>
<add verb="*" path="decision.aspx"
type="Decision#Decision.Decision" />
</httphandlers>
<appsettings />
</configuration>
WHAT I WANT AS OUTPUT:
<?xml version="1.0" ?>
- <configuration>
-<httphandlers>
<add verb="*" path="decision.aspx" type="Decision#Decision.Decision"
/>
</httphandlers>
<appsettings>
<add key="machine1" value="192.168.1.107">
<add key="machine2" value="192.168.1.108">
</appsettings>
</configuration>