在 apache velocity for loop 中过滤数据

filter data in apache velocity for loop

我正在使用 Apache velocity 来解析一个 xml 文件,假设我有以下情况:

我的 XML 包含一个 <animals> 根节点,其中包含一个 <dogs> 节点和 3 个单数子节点 <dog>,每个子节点都有一个 <name> 包含值的节点。

<animals>
    <dogs>
        <dog>
            <name>REX</name>
        </dog> 
        <dog>
            <name>FELIX</name>
        </dog> 
        <dog>
            <name>REX</name>
        </dog> 
    </dogs>
</animals>

在我的速度模板中,我有一个 foreach 循环获取所有 <dog> 节点,如下所示:

#foreach( $dog in $animals.dogs.children() )
    $dog.name.getText() 
#end

所以,这个基本示例有效,但是如果我必须从 foreach 中过滤掉没有 FELIX 作为名称的狗怎么办?例如,仅在名称为 REX 的狗上循环,我尝试使用 IF 语句,但它不适用于 getText(),是否有直接在 foreach 循环中执行此操作的方法?

谢谢。

在 if 语句中而不是

$dog.name.getText()

使用

$dog.name.text

例子

#foreach( $dog in $animals.dogs.children() )
    #if ($dog.name.text != 'whatever')
       ## do something
    #end
#end

4.3 属性

Velocity allows you to access properties through a short-hand notation. The objects to look up the properties must be available through a Velocity variable and the notation consists of a leading variable followed by the dot (".") character and another VTL Identifier.

$customer.address
$purchase.total
$cart.customerDiscount

示例 4.2 有效的 属性 名称

A property name can represent the following elements depending on the object used for look-up:

  • 如果对象有一个get方法,其中属性名字没有被修改,这个方法被调用

  • 否则,如果对象是 Java bean(具有符合 Sun Java Bean 规范的访问 bean 属性的方法),则 bean getter 是执行以访问值

  • 最后,如果用于查找 属性 的对象有 get(String) 方法,则调用此方法。

以第一个例子为例,$customer.address。它可以有多个meanings:1

  • 当对象有getaddress()方法时,调用该方法

  • 当对象是具有 属性 地址的 Java bean 时,调用它的 getter,getAddress()

  • 当对象有方法get(String)时,调用该方法,将地址作为参数传递。

  • 当对象有一个方法isAddress()时,调用这个方法。

Note When a property name refers to a getter method, $obj.property and $obj.Property will both invoke the same method (either getproperty() or getProperty()). However, if the object represented by $obj has a get(String) method, $obj.property and $obj.Property will pass different values to this get(String) method. This can lead to hard-to-find problems. It's a good practice to standardize the capitalization of property names in your application. If you wonder about setting property values, please look up the #set() directive chapter. The setting of properties is discussed there

https://people.apache.org/~henning/velocity/pdf/VelocityUsersGuide.pdf

仅供参考,在 JSTL/EL

中使用了相同的 shorthand