0

我需要从 xml 文件中单独接收所有文本,以接收我使用此代码的特定标签。但我不确定如何解析 XML 中的所有文本,因为 XML 文件不同,我不知道它们的根节点和子节点,但我只需要 xml 中的文本。

try {

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(streamLimiter.getFile());
        doc.getDocumentElement().normalize();

        System.out.println("Root element :"
                + doc.getDocumentElement().getNodeName());
        NodeList nList = doc.getElementsByTagName("employee");
        System.out.println("-----------------------");

        for (int temp = 0; temp < nList.getLength(); temp++) {

            Node nNode = nList.item(temp);
            if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                Element eElement = (Element) nNode;

                NodeList nlList = eElement.getElementsByTagName("firstname")
                        .item(0).getChildNodes();

                Node nValue = (Node) nlList.item(0);

                System.out.println("First Name : "
                        + nValue.getNodeValue());

            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
4

1 回答 1

0

在这篇文章中引用jsight 的回复:Getting XML Node text value with Java DOM

import java.io.ByteArrayInputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


class Test {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws Exception {
    String xml = "<add job=\"351\">\n"
        + "    <tag>foobar</tag>\n"
        + "    <tag>foobar2</tag>\n"
        + "</add>";
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes());
    org.w3c.dom.Document doc = db.parse(bis);
    Node n = doc.getFirstChild();
    NodeList nl = n.getChildNodes();
    Node an, an2;

    for (int i = 0; i < nl.getLength(); i++) {
        an = nl.item(i);
        if (an.getNodeType() == Node.ELEMENT_NODE) {
        NodeList nl2 = an.getChildNodes();

        for (int i2 = 0; i2 < nl2.getLength(); i2++) {
            an2 = nl2.item(i2);
            // DEBUG PRINTS
            System.out.println(an2.getNodeName() + ": type (" + an2.getNodeType() + "):");
            if (an2.hasChildNodes()) {
            System.out.println(an2.getFirstChild().getTextContent());
            }
            if (an2.hasChildNodes()) {
            System.out.println(an2.getFirstChild().getNodeValue());
            }
            System.out.println(an2.getTextContent());
            System.out.println(an2.getNodeValue());
        }

        }
    }
    }
}

输出:

#text: type (3):
foobar
foobar
#text: type (3):
foobar2

根据您的问题调整此代码,它应该可以工作。

于 2012-05-15T14:13:29.110 回答