troubleshooting Question

replace an element in xml with C#

Avatar of swstiller
swstiller asked on
XML.NET ProgrammingC#
4 Comments2 Solutions595 ViewsLast Modified:
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
    <name>Sample Tray</name>
    <name>Dest Tray</name>

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

Any Suggestions?
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 2 Answers and 4 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 2 Answers and 4 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros