【问题标题】:XPath and and or syntax, any shorter way to write this XpathXPath and and or 语法,写这个 Xpath 的任何更短的方法
【发布时间】:2013-02-08 12:12:25
【问题描述】:

我正在过滤一个包含儿童鞋类型的大文件,男鞋和女鞋。

现在我想过滤掉某些类型的女鞋,以下 xpath 有效,但我正在使用的程序有 xpath 长度限制。所以我想知道是否有更短/更有效的方法来构建这个 xpath

/Products/Product[contains(CategoryPath/ProductCategoryPath,'Halbschuhe') and contains(CategoryPath/ProductCategoryPath,'Damen') or  contains(CategoryPath/ProductCategoryPath,'Sneaker') and contains(CategoryPath/ProductCategoryPath,'Damen') or contains(CategoryPath/ProductCategoryPath,'Ballerinas') and contains(CategoryPath/ProductCategoryPath,'Damen')]

编辑:添加了请求的文件示例

<Products>
    <!-- snip -->
    <Product ProgramID="4875" ArticleNumber="GO1-f05-0001-12">
        <CategoryPath>
            <ProductCategoryID>34857489</ProductCategoryID>
            <ProductCategoryPath>Damen &gt; Sale &gt; Schuhe &gt; Sneaker &gt; Sneaker Low</ProductCategoryPath>
            <AffilinetProductCategoryPath>Kleidung &amp; Accessoires?</AffilinetProductCategoryPath>
        </CategoryPath>
        <Price>
            <DisplayPrice>40.95 EUR</DisplayPrice>
            <Price>40.95</Price>
        </Price>
    </Product>
    <!-- snip -->
</Products>

【问题讨论】:

  • 能否添加一个简单的 XML 树示例?特别想看看CategoryPathProductCategoryPath是怎么布局的。

标签: xpath operators


【解决方案1】:

如果您有可用的 XPath 2.0,您应该尝试 matches() 函数,甚至是 tokenize(),正如 Ranon 在他的出色回答中所建议的那样。

使用 XPath 1.0,缩短表达式的一种方法是:

/Products/Product[
    CategoryPath/ProductCategoryPath[
        contains(., 'Damen')
            and (  contains(., 'Halbschuhe')
                or contains(.,    'Sneaker')
                or contains(., 'Ballerinas') )] ]

一个方便的单行器,便于复制粘贴:

/Products/Product[CategoryPath/ProductCategoryPath[contains(.,'Damen') and (contains(.,'Halbschuhe') or contains(.,'Sneaker') or contains(.,'Ballerinas'))]]

我试图完全保留您的表达方式,任何更改都不应该以任何方式改变行为。

还有一些更短的解决方案需要对 XML 结构等进行假设,但这些解决方案可能会以某种隐藏的方式被破坏,如果没有完整的上下文,我们就无法看到,所以我们不会那样做。

【讨论】:

  • 超级这个作品提供了与我冗长的 xpath 完全相同数量的记录,非常感谢!
【解决方案2】:

如果您的 XPath 引擎支持 XPath 2.0,则可以以更方便(并且可能更高效)的方式完成:

//Product[
  CategoryPath/ProductCategoryPath[
    tokenize(., '\s') = ('Halbschuhe', 'Sneaker', 'Ballerinas') and contains(., 'Damen')
  ]
]

fn:tokenize($string, $token) 在正则表达式上拆分字符串(这里使用空格,您也可以只提供空格)。 = 比较基于集合的语义,因此如果左侧的任何字符串等于右侧的任何字符串,则返回 true。

【讨论】:

  • 刚刚尝试过不起作用,因此它不支持 xpath 2.0 或者有其他原因导致它不起作用。知道如何在不使用 xpath 2.0 的情况下缩短它吗?
  • 您收到什么错误信息?如果您告诉我们您使用的是哪个引擎,我们可以告诉您更多关于它是否支持 2.0 的信息。否则你将被困在@Slanecs 的回答中。如果可能,fn:tokenize(...) 应该是首选,因为它可能更快、更通用。
  • 获取 xpath 错误,未找到匹配记录。打算使用 slanec 的方法来寻求帮助。
  • 您使用的是哪个 XPath 引擎/解释器?
  • WP import all, import program for feeds, 半相关问题 你知道一个很好的简单 XML 编辑器程序,你可以用它来打开 XML 文件,然后使用 Xpath 过滤,然后将过滤后的记录保存为 xml 文件.
猜你喜欢
  • 2017-04-04
  • 2022-01-08
  • 1970-01-01
  • 1970-01-01
  • 2014-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-10
相关资源
最近更新 更多