【问题标题】:Dom4j rule does not match all expected nodesDom4j 规则与所有预期节点不匹配
【发布时间】:2009-05-02 20:03:23
【问题描述】:

如果预定义的模式 //authorize 与以下 xml sn-p 中的元素匹配,我正在使用 dom4j 的规则 API 来触发操作。

        <authorize role_required="admin">
        <node title="node which is visible only to admin" path="" >
            <authorize role_required="admin">
                <node title="node which is visible only to admin" path=""/>
            </authorize>
            <authorize role_required="admin">
                <node title="node which is visible only to admin" path="">
                    <authorize role_required="admin">
                    </authorize>
                        <node title="node which is visible only to admin" path=""/>
                </node>
            </authorize>
        </node>
    </authorize>
    <authorize role_deny="admin">
        <node title="Node which is not visible to admin" path=""/>
    </authorize>

不幸的是,它似乎不适用于嵌套元素,只能找到第一级的授权元素。该动作仅触发两次,但有 5 个授权元素。 有人知道如何解决这个问题吗? 提前致谢。

我尝试将授权标签与以下规则匹配:

 Rule authorizationRule = new Rule();
 authorizationRule.setPattern( DocumentHelper.createPattern( "//authorize" ) );
 authorizationRule.setAction( new AuthorizationRule() );

this.stylesheet = new Stylesheet();

this.stylesheet.addRule(authorizationRule);
this.stylesheet.run(document);

规则在第一层的元素上匹配两次。 我用 document.selectNodes 方法交叉检查了 XPath 模式,得到了所有五个元素。

【问题讨论】:

  • 你能用一些示例代码附加这个问题吗?您究竟是如何尝试匹配 元素的? (听起来你的 XPath 有点不对劲,但从提供的信息中很难说。)

标签: java xml xslt dom4j


【解决方案1】:

你的规则有这条线吗?

stylesheet.applyTemplates(node);

请记住,您的规则控制着更深层次的元素。

模式似乎不是用于选择元素,而是用于在遍历树时检查元素是否匹配。如果元素与模式匹配,则调用您的操作,但您有责任在子元素中继续。如果不这样做,则会跳过子元素。

(免责声明:我的理解可能有误,我没有使用dom4j,只是看了cookbook)。

【讨论】:

  • 我只是在用 dom4j 测试这个(并且想知道样式表和规则应该如何在其中工作),看来您完全正确!
【解决方案2】:

我认为Peter nailed the issue;我只是在他的回答之上构建。

Thomas 的代码示例中的这一行有点令人困惑:

 authorizationRule.setAction( new AuthorizationRule() );

...除非 AuthorizationRule 是 Action 的自定义实现,因为这就是 setAction 所需要的。

无论如何,使用以下代码,确实会为每五个“授权”元素调用操作的 run 方法:

Rule authorizationRule = new Rule();
authorizationRule.setPattern(DocumentHelper.createPattern("//authorize"));

final Stylesheet stylesheet = new Stylesheet();                                 
authorizationRule.setAction(new Action(){
    public void run(Node node) throws Exception {
       stylesheet.applyTemplates(node);
    }
 });

stylesheet.addRule(authorizationRule);
stylesheet.run(document);

(仅在将 XML sn-p 更改为格式良好的文档后才有效。)

您需要在动作中使用样式表的方式似乎有点尴尬,而且我不确定这种事情在 dom4j 中是如何应该完成的。很遗憾,像 StylesheetRule 这样的相关类似乎没有充分记录。 (考虑例如方法run(Node node, String mode),其模式参数似乎完全缺乏解释。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多