DOM解析XML遇到的子节点个数问题

xml文件如下:

<?xml version="1.0" encoding="UTF-8"?>

<books>

    <book>book text</book>

</books>

个人以为books的子节点只有1个。

测试如下:

       try {

           DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

           DocumentBuilder builder = factory.newDocumentBuilder();

           Document document = builder.parse(new File("test.xml"));

           Element root = document.getDocumentElement();

           //System.out.println(root.getNodeName());

           NodeList nodeList = root.getChildNodes();

           System.out.println("length =" + nodeList.getLength());

          

       } catch (Exception e) {

           // TODO: handleexception

           e.printStackTrace();

       }

结果如下:

length =3

 

百思不得其解,后来终于测试出来子节点是1Element节点和2Text节点。

修改xml文件并打印测试如下:

<?xml version="1.0" encoding="UTF-8"?>

<books>

before

    <book>book text</book>

after

</books>

 

try {

           DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

           DocumentBuilder builder = factory.newDocumentBuilder();

           Document document = builder.parse(new File("test.xml"));

           Element root = document.getDocumentElement();

           //System.out.println(root.getNodeName());

           NodeList nodeList = root.getChildNodes();

           System.out.println("length =" + nodeList.getLength());

           for(int i = 0; i <nodeList.getLength(); ++i)

           {

              Node node = nodeList.item(i);

              if(node.getNodeType() == Node.TEXT_NODE)

                  System.out.println(node.getNodeValue());

              else if(node.getNodeType() == Node.ELEMENT_NODE)

                  System.out.println(node.getNodeName());

              //System.out.println(node.getNodeType());

           }

              } catch (Exception e) {

           // TODO: handleexception

           e.printStackTrace();

       }

结果如下:

length = 3

    before

       book

    after

原来每个子节点与父节点之间都有默认的Text节点,如果没有赋值的话,节点内容为空,但仍然作为一个空节点存在着。这就是为什么子节点个数为3而不是1

你可能感兴趣的:(xml,exception,测试,File,encoding,books)