【问题标题】:Java: split node with splitText() methodJava:使用 splitText() 方法拆分节点
【发布时间】:2017-01-20 19:00:18
【问题描述】:

我的目标是进行 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 方法?

【问题讨论】:

    标签: java regex xml xpath


    【解决方案1】:

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

    【讨论】:

    • 感谢您的回答,它有效 :) 这段代码还有一些问题,但那是另一回事了。
    猜你喜欢
    • 2021-02-28
    • 2011-11-14
    • 1970-01-01
    • 2014-01-10
    • 1970-01-01
    • 2015-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多