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("/pa rams/param [name='"+t itle+"']") ;
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,newele mentvalue, last);
root.ReplaceChild(newEleme nt,oldElem ent);
doc.Save(filename);
Any Suggestions?
Thanks!!
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("/pa
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,newele
root.ReplaceChild(newEleme
doc.Save(filename);
Any Suggestions?
Thanks!!
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
NP. Glad to help = )
ASKER