For the first time in a long time I needed to update values inside an XML document. I have done this type of action many times in the past and have always hated it. The syntax is clunky and the process is simply painful.
So today when I realized I need to do this, let me just tell you I was NOT looking forward to writing this code. Then I remembered that with .Net 3.5 they added XLinq and it allows you to simply navigate and manipulate XML documents. This was exactly what I was looking for.
In order to figure out how to use XLinq to manipulate a file I turned to the book Linq in Action to find the answer. In the very short time I have had this book, I have found it to be very useful.
Ok, ok, enough chatter, lets get to the problem and how I solved it.
For my task, I need to open a XML Document that is stored as an embedded resource in our application, make changes to it and pass it along as an XML Document. The end goal is to take this document and sent it along to one of our 3rd party vendors via the XML Api.
Here is the Raw XML that needed to be modified
<?xml version="1.0" encoding="utf-8" ?>
Below is the code needed to update this document with the provided values.
In order to use XLinq you need to import System.Xml.Linq
XmlDocument xmlDocument = METHOD TO LOAD XML DOCUMENT HERE
// Convert to an XDoc so we can process this
XDocument xDocument = XDocument.Parse( xmlDocument.OuterXml );
XElement authorizationElement = xDocument.Element( root" ).Element( "authorization" );
authorizationElement.SetElementValue( "username", "SomeValue" );
authorizationElement.SetElementValue( "password", "SomeValue" );
XElement systemElement = xDocument.Element( "root" ).Element( "call" );
systemElement.SetElementValue( "call_name", "SomeValue" );
systemElement.SetElementValue( "call_action", "SomeValue" );
systemElement.SetElementValue( "search_type", "SomeValue" );
systemElement.SetElementValue( "search_value", "SomeValue" );
// convert the xDocument back to an XML document for later usage
xmlDocument.LoadXml( xDocument.ToString() );
So as you can see I can very easily and very quickly manipulate this document with the correct values. And because the syntax is in a fluent style it is VERY easy to read.
Till next time,
05-01-2008 4:26 PM