jorame
jorame

Reputation: 2207

How to change the data within elements in a XML file using C#?

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.

Upvotes: 0

Views: 5455

Answers (3)

Xiaodan Mao
Xiaodan Mao

Reputation: 1706

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.

Upvotes: 0

gdp
gdp

Reputation: 8242

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")

Upvotes: 1

John Pankowicz
John Pankowicz

Reputation: 4451

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

Upvotes: 1

Related Questions