gpt4 book ai didi

Java:使用 splitText() 方法分割节点

转载 作者:太空宇宙 更新时间:2023-11-04 11:51:38 24 4
gpt4 key购买 nike

我的目标是进行 XML 输入,将节点中的一些文本替换为 XML DOM 元素并生成 XML 输出。我的 XML 输入和预期输出可以找到 here, in this SO question .

这是我的java代码:

private static void textTransformCitations(Document document) 
{
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "/article/body/sec/p/text()";
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(document, XPathConstants.NODESET);

for (int i = 0; i < nodeList.getLength(); i++)
{
Node textNode = nodeList.item(i);
Matcher m = Pattern.compile("\\[(\\d+)\\]").matcher(textNode.getNodeValue());
while (m.find())
{
Text number = textNode.splitText(m.start(1));
textNode = number.splitText(m.group(1).length());
Element xref = document.createElement("xref");
xref.setAttribute("rid", "bib" + m.group(1));
xref.setAttribute("ref-type", "bibr");
number.getParentNode().replaceChild(number, xref);
xref.appendChild(number);
}
}
} // Added by edit!

显然问题是 splitText() 只能用于 Text 接口(interface):

textNode.splitText

哪个 textNode 变量不是。但我已明确声明使用 XPath 从节点检索文本。

我该怎么做才能使这段代码正常工作?
在这种情况下如何使用 splitText 方法?

最佳答案

将语句 Node textNode = nodeList.item(i); 更改为 Text textNode = (Text)nodelist.item(i);

关于Java:使用 splitText() 方法分割节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41770636/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com