简体   繁体   English

创建自定义XPath函数以修改Java中的节点集

[英]Creating a custom XPath function to modify a node-set in Java

I am creating a custom XPath function in Java that modifies the text-nodes in a node-set. 我正在用Java创建一个自定义XPath函数,该函数可以修改节点集中的文本节点。 I need to pass in a node-set, have the code loop through every node and return a node-set. 我需要传递一个节点集,让代码遍历每个节点并返回一个节点集。 I have seen many examples of custom XPath functions that modify strings, but none that take in a node set and return a node set successfully. 我已经看到了许多自定义XPath函数的示例,这些示例可以修改字符串,但是没有一个示例可以接受节点集并成功返回节点集。 I also don't know how to map the returning node-set. 我也不知道如何映射返回的节点集。

Take this source XML for example. 以这个源XML为例。

<Library>
    <Bookshelf>
        <Book>alice in wonderland</Book>
        <Book>the giving tree</Book>
            <Author>shel silverstein</Author>
    </Bookshelf>
</Library>

Then I want this to be my target XML. 然后,我希望它成为我的目标XML。 I chose to capitalize the first letter of each word, but this is just an example. 我选择将每个单词的首字母大写,但这只是一个例子。 Don't worry about the text modification part, I got that. 不用担心文本修改部分,我明白了。

<Library>
    <Bookshelf>
        <Book>Alice In Wonderland</Book>
        <Book>The Giving Tree</Book>
            <Author>Shel Silverstein</Author>
    </Bookshelf>
</Library>

The biggest thing here is that I want to implement this as a custom XPath function using Java so that it can be drag-and-dropped in Designer mode. 这里最大的事情是,我想使用Java将其实现为自定义XPath函数,以便可以在Designer模式下将其拖放。 And I am using a File Adapter on each side of this transformation, so the structure of all the nodes is already given and I have to make my results fit in. 而且我在此转换的每一侧都使用了文件适配器,因此所有节点的结构都已经给出,我必须使结果适合。

You need to create your own implementation of NodeList. 您需要创建自己的NodeList实现。 Something like what I use: 像我用的东西:

package org.gramar.model;

import java.util.List;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class NodeArray implements NodeList {

    private Node nodes[];

    public NodeArray(Node[] nodes) {
        this.nodes = nodes;
    }

    public NodeArray(List<Node> nodes) {
        this.nodes = new Node[nodes.size()];
        nodes.toArray(this.nodes);
    }

    @Override
    public Node item(int index) {
        return nodes[index];
    }

    @Override
    public int getLength() {
        return nodes.length;
    }

}

Your XPathFunction code would have something like this: 您的XPathFunction代码将具有以下内容:

ArrayList<Node> nodes = ... logic to gather the nodes you want to return
return new NodeArray(nodes);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM