【问题标题】:Find through multiple attributes in XML通过 XML 中的多个属性查找
【发布时间】:2008-12-09 19:04:07
【问题描述】:

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

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

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

【问题讨论】:

  • 两点。首先,XML 看起来无效。其次,您使用的是什么语言/环境?例如,我知道如何在 C# 中执行此操作...
  • 无效的 XML(
    标签)仅仅是因为他不知道如何将某些内容格式化为代码。我已经更正了。

标签: xml search xml-attribute


【解决方案1】:

要在您提供的 XML 的 sn-p 中搜索您想要的内容,您需要以下 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

【讨论】:

    【解决方案2】:

    搜索 XML 是 XPath 的用途。您没有指定您使用的语言,但here's an article 在 Java 中使用 XPath 处理 XML,here's one 使用 C#。

    【讨论】:

      【解决方案3】:

      这是关于XPath 表达式的常见问题解答

      可以使用boolean operators“and”和“or”以及使用XPath函数not()将一个或多个XPath表达式(其评估类型为布尔值)连接在一起。

      请注意,这些名称都是小写的。 XPath 区分大小写,并且这些名称的任何其他大写形式(例如“AND”)都不会被识别为逻辑运算符的名称。

      因此,在这种特殊情况下,所需的 XPath 表达式将如下所示:

      /*/*/field[@Username = your-ds-username and @UserPassword = your-ds-UserPassword]

      其中your-ds-usernameyour-ds-UserPassword 应替换为您要从数据集中使用的相应值。

      【讨论】:

      • 为什么使用“/*/*”(而不是“//”)?我想 - 当您对元素名称不明确时,您也可以不具体说明嵌套深度。还是我忽略了什么?
      • @Tomalak:避免使用“//”缩写,因为它会导致搜索完整的文档树。当我们知道文档的结构时,我们可以只指定必要的级别和名称。在这种情况下,名称是一个级别中唯一出现的名称,因此不检查名称会更有效
      【解决方案4】:

      要在 XML 标签的情况下搜索多个属性,我们可以使用以下 XPATH /APIS/API/字段[@Username='username1'][@UserPassword='password1']

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-01-23
        • 1970-01-01
        • 1970-01-01
        • 2014-07-01
        • 2017-05-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多