我的目标是进行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界面:


  textNode.splitText


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

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

最佳答案

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

10-04 14:12