在XML中查找多个属性 [英] Find through multiple attributes in XML
问题描述
我正在尝试搜索XML中的多个属性:
I'm trying to search multiple attributes in XML :
<APIS>
<API Key="00001">
<field Username="username1" UserPassword="password1" FileName="Filename1.xml"/>
<field Username="username2" UserPassword="password2" FileName="Filename2.xml"/>
<field Username="username3" UserPassword="password3" FileName="Filename3.xml"/>
</API>
</APIS>
我需要检查字段"中的用户名和UserPassword值是否都是我要与数据集值进行比较的值,有没有一种方法可以检查多个属性(AND条件)而无需编写自己的使用逻辑标志和中断循环.
I need to check if in the "field" the Username AND UserPassword values are both what I am comparing with my Dataset values, is there a way where I can check multiple attributes (AND condition) without writing my own logic of using Flags and breaking out of loops.
有XMLDoc的内置函数吗?任何帮助,将不胜感激!
Is there a built in function of XMLDoc that does it? Any help would be appreciated!
推荐答案
要在提供的XML代码段中搜索所需内容,您需要以下XPath表达式:
To search for what you want in the snippet of XML you provided, you would need the following XPath expression:
/APIS/API/field[@Username='username1' and @UserPassword='password1']
如果用户名和密码匹配,这将返回某些内容,否则将返回
This would either return something, if user name and password match - or not if they don't.
当然,XPath表达式只是一个字符串-例如,您可以使用在表单字段中输入的值来动态构建它.
Of couse the XPath expression is just a string - you can build it dynamically with values that were entered into a form field, for example.
如果您告诉您所使用的语言/环境,此处发布的代码示例可能会变得更加具体.
If you tell what language/environment you are in, code samples posted here will likely get more specific.
这是在C#中执行此操作的一种方法(VB.NET是类似的):
This is a way to do it in C# (VB.NET is analogous):
// make sure the following line is included in your class
using System.Xml;
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load("your XML string or file");
string xpath = "/APIS/API/field[@Username='{0}' and @UserPassword='{1}']";
string username = "username1";
string password = "password1";
xpath = String.Format(xpath, username, password);
XmlNode userNode = xmldoc.SelectSingleNode(xpath);
if (userNode != null)
{
// found something with given user name and password
}
else
{
// username or password incorrect
}
请注意,用户名和密码都不能包含单引号,否则以上示例将失败.这是有关此特殊性的一些信息.
Be aware that neither user names nor passwords can contain single quotes, or the above example will fail. Here is some info on this peculiarity.
还有Microsoft提供的操作方法:如何:使用System.Xml.XmlDocument类在Visual C#.NET中执行XPath查询
There is also a How-To from Microsoft available: HOW TO: Use the System.Xml.XmlDocument Class to Execute XPath Queries in Visual C# .NET
这篇关于在XML中查找多个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!