[英]When using setParameter with a node-set, it raises exception “Invalid conversion from java.lang.String to node-set”
[英]Creating a custom XPath function to modify a node-set in Java
我正在用Java創建一個自定義XPath函數,該函數可以修改節點集中的文本節點。 我需要傳遞一個節點集,讓代碼遍歷每個節點並返回一個節點集。 我已經看到了許多自定義XPath函數的示例,這些示例可以修改字符串,但是沒有一個示例可以接受節點集並成功返回節點集。 我也不知道如何映射返回的節點集。
以這個源XML為例。
<Library>
<Bookshelf>
<Book>alice in wonderland</Book>
<Book>the giving tree</Book>
<Author>shel silverstein</Author>
</Bookshelf>
</Library>
然后,我希望它成為我的目標XML。 我選擇將每個單詞的首字母大寫,但這只是一個例子。 不用擔心文本修改部分,我明白了。
<Library>
<Bookshelf>
<Book>Alice In Wonderland</Book>
<Book>The Giving Tree</Book>
<Author>Shel Silverstein</Author>
</Bookshelf>
</Library>
這里最大的事情是,我想使用Java將其實現為自定義XPath函數,以便可以在Designer模式下將其拖放。 而且我在此轉換的每一側都使用了文件適配器,因此所有節點的結構都已經給出,我必須使結果適合。
您需要創建自己的NodeList實現。 像我用的東西:
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;
}
}
您的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.