Link to home
Start Free TrialLog in
Avatar of swstiller
swstiller

asked on

replace an element in xml with C#

I am trying to replace an element in an xml file.  I have a solution, but it seems way to ugly.  I am asking if there is a more elegant way to solve this problem.

1. the xml file.  Here is a simplified segment of the file to show the structure
<params>
  <param>
    <name>Sample Tray</name>
    <default>Tray01</default>
    <units>each</units>
  </param>
  <param>
    <name>Dest Tray</name>
    <default>Tray02</default>
    <units>each</units>
  </param>
<params>

I want to replace the default value for one of the trays (Sample Tray for this example)
Here is what I did:
XmlDocument doc  (contains the xml file above)
XmlNode oldElement;
XmlElement root = doc.DocumentElement;
string title= "Sample Tray";
string newelementvalue = "TRAYXX";
oldElement = root.SelectSingleNode("/params/param[name='"+title+"']");
string str = oldElement.InnerXml;
int start = str.IndexOf("<default>");
int end = str.IndexOf("</default>");
string first = str.Substring(0, start + 8+1);
string last = str.Substring(end);
XmlElement newElement= doc.CreateElement("param");
newElement.InnerXml = string.Concat(first,newelementvalue,last);
root.ReplaceChild(newElement,oldElement);
doc.Save(filename);

Any Suggestions?
Thanks!!
ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of swstiller
swstiller

ASKER

Thank you so much. Tried it. It works. I hate to do cruddy programming when I can help it.  Not all that familiar with manipulating Xml.  Kudos.
NP. Glad to help  = )