您的位置:首页 > 其它

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

2010-10-15 17:08 495 查看
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; 百思不得其解,后来终于测试出来子节点是1个Element节点和2个Text节点。修改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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息