具有可变多条件的 XPath 查询

swo*_*ent 1 xml xslt xpath

长期聆听者,初次来电者。我对 XPath 比较陌生,并查看了此处和其他地方的其他几个线程,但我似乎无法使查询正常工作,任何帮助都会很棒。

我有如下 XML:

<catalog>
  <book pgid="28054" lang="en">
    <title>The Brothers Karamazov</title>
    <author>Dostoyevsky, Fyodor</author>
    <friendly_title>The Brothers Karamazov by Fyodor Dostoyevsky</friendly_title>
    <file>
      <type>ePub</type>
      <path>cache/generated/28054/</path>
      <name>pg28054.epub</name>
      <size>800</size>
    </file>
    <file>
      <type>PDF</type>
      <path>2/8/0/5/28054/</path>
      <name>28054-pdf.pdf</name>
      <size>5829</size>
    </file>
    <file>
      <type compression="zipped">PDF</type>
      <path>2/8/0/5/28054/</path>
      <name>28054-pdf.zip</name>
      <size>1693</size>
    </file>
    <file>
      <type encoding="utf-8" compression="zipped">Text</type>
      <path>2/8/0/5/28054/</path>
      <name>28054-0.zip</name>
      <size>726</size>
    </file>
  </book>
</catalog>
Run Code Online (Sandbox Code Playgroud)

(catalog 是根元素,在这个例子中没有<contributor>元素)

我有关于作者、贡献者、标题和语言搜索的查询,但我在添加文件类型条件时遇到了麻烦。此查询查找作者或贡献者包含“陀思妥耶夫斯基”和标题包含“兄弟”且语言为“en”的书籍正在工作(即给出预期结果),但如果有更好的编写方式,我会全力以赴:

/catalog//book/*[(contains(self::author,'Dostoyevsky') or contains(self::contributor,'Dostoyevsky')) and contains(../title,'Brothers') and ../@lang = 'en']
Run Code Online (Sandbox Code Playgroud)

无法开始工作的是将查询结果限制为某种类型的文件,即附加and ../file/type='PDF'或其他内容。|工会也没有运气。

提前致谢。

哦,如果重要的话,查询需要动态构建(从表单输入),所以它需要保留一个通用语法,可以与任意数量的用户提供的标准一起使用。

Vin*_*net 5

如果我猜对了,这应该有效:

/catalog[file/type='PDF']//book/*[(contains(self::author,'Dostoyevsky') or contains(self::contributor,'Dostoyevsky')) and contains(../title,'Brothers') and ../@lang = 'en']
Run Code Online (Sandbox Code Playgroud)

请注意,过滤器直接位于catalog元素上。

如果您尝试获取book元素,也许您应该使用/catalog[file/type=...]//book[test1][test2][test3]...不同的约束。每个新测试都充当过滤器。