我正在尝试使用XPath从xml文档中选择特定值。 xml存储在字符串varibale“tmp”中。此xml是在外部API上执行查询的结果。
示例XML内容:
<?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>
在后面的代码中使用XPATH我希望能够选择并且仅针对id = adsl,然后将值存储在字符串变量中供以后使用。我希望在没有使用单独的xslt样式表的情况下实现这一目标。
以下是我为此编写的代码,但我收到错误:
//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 variable Linespeedval
string Linespeedval = Check.ToString();
//Adding a control to display the xpath results of the "tmp" xml objectt
AvailabilityCheckerResults2.Controls.Add(new LiteralControl(Linespeedval));
非常感谢任何帮助!提前谢谢!
答案 0 :(得分:1)
strExpression1 = "/Results/Checks/Check[@id = 'adsl']/Linespeed";
//or strExpression1 = "//Checks/Check[@id = 'adsl']/Linespeed";
//doc has no namespace
Check = root.SelectSingleNode(strExpression1);
....
string Linespeedval = Check.InnerText;
答案 1 :(得分:0)
看看这篇文章。它有一步一步的指令,使用xpath解析xml。 How to query XML with an XPath expression by using Visual C#