Friday, December 23, 2011

Editing XML


If you need to edit an XML document, there is an easier way than trying to manually edit the string.
          
XmlDocument xpathDocument = new XmlDocument();
byte[] byteArray = Encoding.ASCII.GetBytes(xmlData); 
//xmlData is a valid XML object stored as a string.
xpathDocument.Load(new MemoryStream( byteArray ));
XPathNavigator xpathNavigator = xpathDocument.CreateNavigator();
  
//Update the xmlData's OpenText node (child of root).
xpathNavigator.SelectSingleNode(".//OpenText").SetValue("New Open Text Value");

Here is the sample XML schema:
<BidInfo>
<OpenText>Some value</OpenText>
</BidInfo>

Note that if you try to edit an object of type XPathDocument it won't work out for you, although the error messages may not immediately make it clear why. The XPathDocument class "Provides a fast, read-only, in-memory representation of an XML document by using the XPath data model. Pasted from <http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathdocument.aspx

No comments:

Post a Comment