gpt4 book ai didi

xml - 通过 XML 中的多个属性查找

转载 作者:数据小太阳 更新时间:2023-10-29 01:43:51 26 4
gpt4 key购买 nike

我正在尝试在 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>

我需要检查“字段”中的用户名和用户密码值是否都是我正在与我的数据集值进行比较的值,有没有一种方法可以在不编写自己的使用逻辑的情况下检查多个属性(和条件)标记和跳出循环。

是否有一个内置的 XMLDoc 函数可以做到这一点?任何帮助,将不胜感激!

最佳答案

要在您提供的 XML 片段中搜索您想要的内容,您需要以下 XPath 表达式:

/APIS/API/field[@Username='username1' and @UserPassword='password1']

如果用户名和密码匹配,这将返回一些东西 - 如果不匹配,则不返回。

当然,XPath 表达式只是一个字符串 - 例如,您可以使用输入到表单字段中的值动态构建它。

如果您告诉您所处的语言/环境,此处发布的代码示例可能会更加具体。

这是一种在 C# 中实现的方法(VB.NET 是类似的):

// 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
}

请注意,用户名和密码都不能包含单引号,否则上面的示例将失败。这是 some info on this peculiarity .

还有来自 Microsoft 的操作方法:HOW TO: Use the System.Xml.XmlDocument Class to Execute XPath Queries in Visual C# .NET

关于xml - 通过 XML 中的多个属性查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/353843/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com