0

I'm kind of new to XML files in C# ASP.NET. I have a XML in the below format:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Installation>
  <ServerIP>192.168.20.110</ServerIP>
  <DB_Name>USTCKT1</DB_Name>
  <Username>jorame</Username>
  <Password>Cru$%e20</Password>
  <Table_PreFix>TCK</Table_PreFix>
</Installation>

I need to change the values within each element. For example, when an user clicks I should be able to replace 192.168.20.110 with 192.168.1.12.

How can I accomplish this? Any help will be really appreciated.

jorame
  • 2,147
  • 12
  • 41
  • 58

3 Answers3

1

You can do something like this using the XDocument class:

XDocument doc = XDocument.Load(file.xml);
doc.Element("Installation").Element("ServerIP").Value = "192.168.1.12";
//Update the rest of the elements
doc.Save(file.xml);

More Details

If you run into namespace issues when selecting your elements you will need to include the xml namespace in the XElement selectors eg doc.Element(namspace + "Installation")

gdp
  • 8,032
  • 10
  • 42
  • 63
1

You should look at using the methods in the XDocument class. http://msdn.microsoft.com/en-us/library/bb301598.aspx

Specifically look at the methods: Load(string) - to load an XML file, Element() - to access a specific element and Save(string) - to save the XML document. The page on Element() has some sample code which can help. http://msdn.microsoft.com/en-us/library/system.xml.linq.xcontainer.element.aspx

John Pankowicz
  • 4,203
  • 2
  • 29
  • 47
0

In general, you can do it in the following steps:

  1. Create a new XmlDocument object and load the content. The content might be a file or string.
  2. Find the element that you want to modify. If the structure of your xml file is too complex, you can use xpath you find what you want.
  3. Apply your modification to that element.
  4. Update your xml file.

Here is a simple demo:

    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load("file.xml"); // use LoadXml(string xml) to load xml string
    string path = "/Installation/ServerIP";
    XmlNode node = xmlDoc.SelectSingleNode(path); // use xpath to find a node
    node.InnerText = "192.168.1.12"; // update node, replace the inner text
    xmlDoc.Save("file.xml"); // save updated content   

Hope it's helpful.

Xiaodan Mao
  • 1,648
  • 2
  • 17
  • 30
  • Would you mind showing how would you read what's inside the node? – jorame Mar 12 '13 at 02:47
  • @jorame My pleasure. XmlNode has many useful properties for you.(http://msdn.microsoft.com/en-us/library/system.xml.xmlnode_properties.aspx) Let's take "ServerIP" as an example. node.InnerText will return "192.168.1.12", if you have an attribute in the node, you can use node.Attributes["attributeName"] to get this attribute. – Xiaodan Mao Mar 12 '13 at 03:27
  • Thank you so much for all your help. I was able to accomplish the process. – jorame Mar 12 '13 at 03:31