Getting XML Node text value with Java DOM

后端 未结 4 1251
滥情空心
滥情空心 2020-11-27 06:16

I can\'t fetch text value with Node.getNodeValue(), Node.getFirstChild().getNodeValue() or with Node.getTextContent().

My XML

4条回答
  •  囚心锁ツ
    2020-11-27 07:07

    I'd print out the result of an2.getNodeName() as well for debugging purposes. My guess is that your tree crawling code isn't crawling to the nodes that you think it is. That suspicion is enhanced by the lack of checking for node names in your code.

    Other than that, the javadoc for Node defines "getNodeValue()" to return null for Nodes of type Element. Therefore, you really should be using getTextContent(). I'm not sure why that wouldn't give you the text that you want.

    Perhaps iterate the children of your tag node and see what types are there?

    Tried this code and it works for me:

    String xml = "\n" +
                 "    foobar\n" +
                 "    foobar2\n" +
                 "";
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes());
    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

    Output was:

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

提交回复
热议问题