I am trying to select specific values from a xml document using XPath. The xml is stored into a string varibale “tmp”. This xml is the result of a query performed on a external API.
sample XML contents:
<?xml version="1.0" encoding="ISO-8859-1"?>
<Results>
<Checks>
<Check id="wbc">
<Linespeed>6000 </Linespeed>
<Provider>BT WBC </Provider>
</Check>
<Check id="adsl">
<Linespeed>2048 </Linespeed>
<Provider>BT ADSL </Provider>
</Check>
</Checks>
</Results>
Using XPATH in code behind I want to be able to select the <Linespeed> and <Provider> only for id=adsl, then store the value in a string variable for later use. I want to achieve this withouth the use of a separate xslt stylesheet. Any assistance on this will be greatly appreciated!
Thanks in advance
Thanks to everyone for the assistance, using the xpath expression I now want to actually put it to use as follows:
//Creating an XPATH epression
String strExpression1;
strExpression1 = "Results/Checks/Check[@id = 'adsl']/Linespeed";
//Loading the xml document
XmlDocument doc;
doc = new XmlDocument();
doc.LoadXml(tmp);
//Create an XmlNamespaceManager to resolve the default namespace.
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("bk", "urn:schemas-microsoft-com:xslt");
//Selecting Linespeed from Check id='adsl'
XmlNode Check;
XmlElement root = doc.DocumentElement;
Check = root.SelectSingleNode(strExpression1, nsmgr);
//Assigning the the results of the XPATH expression to the string variable Linespeedval
string Linespeedval = Check.ToString();
//Adding a control to display the xpath results of the xml query
AvailabilityCheckerResults2.Controls.Add(new
LiteralControl(Linespeedval));
In theory I should be able to see the value of being displayed on a page inside of PlaceHolder named “AvailabilityCheckerResults2”, but I get a error instead. Is there a way to assign the results from the xpath expression to a string variable? Thanks again
The xpath expression to select
<Linespeed/>and<Provider/>for<Check id="adsl"/>is :
//Linespeed[ancestor::Check[@id = 'adsl']]<– This selects all Linespeed nodes whose ancestor is a check element with id = adslAlternatively you could use something like :
This selects the line speed which is a child of a Check with @id = ‘adsl’ as it stands in your document.
For the Provider you can use the same methodology.