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
相关文章推荐
- Google Weather API返回XML的SAX和DOM解析当中遇到的问题及解决
- dom解析xml之中文乱码问题
- 开发自动完成功能中遇到的几个问题---javascript+XMLHTTP+DOM
- javascript下有关dom以及xml节点访问兼容问题
- Dom4j解析XML中遇到的一些问题
- 使用Jsoup库解析HTML、XML或URL链接中的DOM节点
- DOM解析XML的缩进问题(JAVA)
- Java DOM解析Xml中文乱码问题
- HttpParser解析节点遇到的不解问题
- 使用DOM解析XML的文件属性名和属性值、节点名和节点值
- 解析xml时遇到的一些问题
- 关于利用Schema解析XML,生成、编辑XML的节点问题
- 【慕课笔记】2-3 应用DOM方式解析XML—使用 DOM 解析XML 文件的节点名和节点值
- 【第三篇日记】C#解析XML文档和excel文档(弄GoogleEarth时遇到的一个问题,作为一个初学者就大补XML的内容)
- javascript下有关dom以及xml节点访问兼容问题
- jaxb解析xml遇到的问题
- 解析xml时遇到的一些问题
- DOM解析XML解决空格问题
- Java DOM解析Xml中文乱码问题
- Android使用DOM来编辑XML时遇到的问题——无法保存