使用XPath查询XML文档对象
本文关键字:文档 对象 XML 查询 XPath 使用 | 更新日期: 2023-09-27 18:08:54
我目前有一个web部件与提交按钮和两个文本字段的电话号码和邮政编码。当在文本字段中输入电话号码和邮政编码并按下提交按钮时,我希望能够提交一个查询字符串,该字符串用于查询和外部API,然后以XML文档对象的形式返回查询结果。然后,我需要使用XPath查询该对象以显示结果,然后格式化或将结果转换为HTML。首先:
-
我已经创建了XML文档对象(在一个类中),但我不太确定如何使用XPath查询这个对象来检索结果。
-
我也不太确定如何连接提交按钮来执行上面提到的XMLDocument对象中的查询字符串
下面是XMLDocument Object,它将查询外部API并返回结果。代码中没有错误,表明到目前为止一切正常:
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml; // needed for the XML document object
using System.Xml.XPath; //needed to use Xpath to query the XMLDocument object
using System.Xml.Xsl; //needed to convert xml into HTML hopefully
namespace ACWebPart.VisualWebPart1
{
public partial class VisualWebPart1UserControl : UserControl
{
private XmlDocument performXmlCheck(string user, string pass, string phone, string postcode,
string checks, string options)
{
//creating the XMLDocument object
XmlDocument xml = new XmlDocument();
//creating the query to run against the server
string url = String.Format("http://api.samknows.com/checker.do?user= {0} &pass={1} &phone={2}
&postcode={3} &checks={4} &options={5} &output=xml", user, pass, phone, postcode, checks,
options);
//to catch errors a try and catch will be created
try
{
//querying the server, parse the XML and store it
xml.Load(url);
}
catch
{
//if an execption is encountered (Server unreachable, HTTP500, HTTP 404, etc) return null
return null;
}
return xml;
}
protected void Page_Load(object sender, EventArgs e)
{
//creating the event habdler for the submit button
cmdSubmit.Click += new EventHandler(cmdSubmit_Click);
//Live validation of input text boxes to ensure they are not empty and have the correct input
format
TextBox1.Attributes.Add("OnFocus", "if(this.value == 'Phone number') {this.value='',
this.style.borderColor='#c4c4c4', this.style.color='#676767', this.style.fontStyle='normal'};");
TextBox1.Attributes.Add("OnBlur", "if(this.value == '') {this.value='Phone number',
this.style.color='red', this.style.fontStyle='italic', this.style.borderColor='red'};");
TextBox2.Attributes.Add("OnFocus", "if(this.value == 'Postcode's) {this.value='',
this.style.borderColor='#c4c4c4', this.style.color='#676767', this.style.fontStyle='normal'};");
TextBox2.Attributes.Add("OnBlur", "if(this.value == '') {this.value='Postcode',
this.style.color='red', this.style.fontStyle='italic', this.style.borderColor='red'};");
}
void cmdSubmit_Click(object sender, EventArgs e)
{
}
}
}
我在Sharepoint 2010中没有做过很多关于XML的事情,所以任何关于上面第1点和第2点的帮助和帮助都将非常感谢!
Thanks in advance
要使用XPath在XmlDocument
中选择节点,可以使用SelectSingleNode和SelectNodes方法。