16

Node.getTextContent() 返回当前节点及其后代的文本内容。

有没有办法获取当前节点的文本内容,而不是后代的文本。

例子

<paragraph>
    <link>XML</link>
    is a 
    <strong>browser based XML editor</strong>
    editor allows users to edit XML data in an intuitive word processor.
</paragraph>

预期产出

paragraph = is a editor allows users to edit XML data in an intuitive word processor.
link = XML
strong = browser based XML editor

我试过下面的代码

String str =            "<paragraph>"+
                            "<link>XML</link>"+
                            " is a "+ 
                            "<strong>browser based XML editor</strong>"+
                            "editor allows users to edit XML data in an intuitive word processor."+
                        "</paragraph>";

        org.w3c.dom.Document domDoc = null;
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder;

        try {
            docBuilder = docFactory.newDocumentBuilder();
            ByteArrayInputStream bis = new ByteArrayInputStream(str.getBytes());
            domDoc = docBuilder.parse(bis);         
        } catch (ParserConfigurationException e1) {         
            e1.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }       

        DocumentTraversal traversal = (DocumentTraversal) domDoc;
        NodeIterator iterator = traversal.createNodeIterator(
                domDoc.getDocumentElement(), NodeFilter.SHOW_ELEMENT, null, true);

        for (Node n = iterator.nextNode(); n != null; n = iterator.nextNode()) {           
            String tagname = ((Element) n).getTagName();
            System.out.println(tagname + "=" + ((Element)n).getTextContent());
        }

但它给出了这样的输出

paragraph=XML is a browser based XML editoreditor allows users to edit XML data in an intuitive word processor.
link=XML
strong=browser based XML editor

请注意,段落元素包含我不想要的链接文本和标记。请提出一些想法?

4

4 回答 4

15

您想要的是过滤节点的子节点<paragraph>以仅保留节点类型的子节点Node.TEXT_NODE

这是将返回您所需内容的方法示例

public static String getFirstLevelTextContent(Node node) {
    NodeList list = node.getChildNodes();
    StringBuilder textContent = new StringBuilder();
    for (int i = 0; i < list.getLength(); ++i) {
        Node child = list.item(i);
        if (child.getNodeType() == Node.TEXT_NODE)
            textContent.append(child.getTextContent());
    }
    return textContent.toString();
}

在您的示例中,这意味着:

String str = "<paragraph>" + //
        "<link>XML</link>" + //
        " is a " + //
        "<strong>browser based XML editor</strong>" + //
        "editor allows users to edit XML data in an intuitive word processor." + //
        "</paragraph>";
Document domDoc = null;
try {
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    ByteArrayInputStream bis = new ByteArrayInputStream(str.getBytes());
    domDoc = docBuilder.parse(bis);
} catch (Exception e) {
    e.printStackTrace();
}
DocumentTraversal traversal = (DocumentTraversal) domDoc;
NodeIterator iterator = traversal.createNodeIterator(domDoc.getDocumentElement(), NodeFilter.SHOW_ELEMENT, null, true);
for (Node n = iterator.nextNode(); n != null; n = iterator.nextNode()) {
    String tagname = ((Element) n).getTagName();
    System.out.println(tagname + "=" + getFirstLevelTextContent(n));
}

输出:

paragraph= is a editor allows users to edit XML data in an intuitive word processor.
link=XML
strong=browser based XML editor

它所做的是迭代节点的所有子节点,只保留 TEXT(因此不包括评论、节点等)并累积它们各自的文本内容。

没有直接的方法NodeElement仅获取第一级的文本内容。

于 2012-08-30T07:38:39.160 回答
3

如果您将最后一个 for 循环更改为以下循环,它的行为将如您所愿

for (Node n = iterator.nextNode(); n != null; n = iterator.nextNode()) {           
    String tagname = ((Element) n).getTagName();
    StringBuilder content = new StringBuilder();
    NodeList children = n.getChildNodes();
    for(int i=0; i<children.getLength(); i++) {
        Node child = children.item(i);
        if(child.getNodeName().equals("#text"))
            content.append(child.getTextContent());
    }
    System.out.println(tagname + "=" + content);
}
于 2012-08-30T07:38:06.813 回答
2

我使用 Java 8 流和一个辅助类来做到这一点:

import java.util.*;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class NodeLists
{
    /** converts a NodeList to java.util.List of Node */
    static List<Node> list(NodeList nodeList)
    {
        List<Node> list = new ArrayList<>();
        for(int i=0;i<nodeList.getLength();i++) {list.add(nodeList.item(i));}
        return list;
    }
}

接着

 NodeLists.list(node)
.stream()
.filter(node->node.getNodeType()==Node.TEXT_NODE)
 .map(Node::getTextContent)
 .reduce("",(s,t)->s+t);
于 2015-03-25T10:08:47.613 回答
1

隐式地对实际节点文本没有任何功能,但通过一个简单的技巧就可以做到。询问 node.getTextContent() 是否包含“\n”,如果是这种情况,则实际节点没有任何文本。

希望这有帮助。

于 2016-04-15T13:05:33.187 回答