dynamically converting XPath to Linq to XML

Asked By viswa rao
06-Sep-10 11:17 PM
Earn up to 0 extra points for answering this tough question.

Based on XPath I have to serach for atag and replace its contents.
Here is my XML:
<?xml version="1.0" encoding="utf-8" ?>
<root>
<creditcard>
<number>19834209</number>
<expiry>02/02/2002</expiry>
</creditcard>
<name id="1">
<first>Mary</first>
<mi>V</mi>
<last>Jones</last>
</name>
<personal>
<dob>01011966</dob>
<gender>male</gender>
</personal>
   <signature>asfu90235r789Z&*()%%^</signature>
</root>

The Xpath is handed to me by SQL call. So I don’t know contents/levels in the Xpath. As an example SQL returns me Xpath as root//Signature.  I want to be able to get value of the element pointed to by Xpath and replace it with new content.  Can someone please tell me how can I do this with Linq?

  re: dynamically converting XPath to Linq to XML

Indranil Chatterjee replied to viswa rao
04-Jan-11 04:27 AM

Try the following code:

var doc = XDocument.Load("XMLFile1.xml");//XMLFile1.xml contains the xml fragment supplied by you
var element = doc.XPathSelectElement("root//signature");//Here you can supply any Xpath as parameter
element.Value = "myValue";
doc.Save("XMLFile2.xml");
/*







There are multiple methods for using Xpath
If you expect a single element to be returned, use XPathSelectElement
If you expect multiple elements, use XPathSelectElements
If you expect any node, then use XPathEvaluate
There are overloads for each of these which take an IXmlNamespaceResolver in case you have to work with Xml namespaces




*/

// Please note, the xml fragment provided by you has &* as a part of the value for signature element, which was throwing errors. It's prob'ly not a valid value. I had to replace it with some text. Please check this out.
Create New Account