我将以下xml作为字符串:
private static final String xmlStr = "\n" + " ";\n" + " \n" + "emp \n" + "John Smith \n" + "\n" + " \n" + "age \n" + "22 \n" + "\n" + " \n" + "Birth Date \n" + "02/05/1978 \n" + "\n" + " \n" + "password \n" + "ye63633 \n" + "
该参数可以用任何字符串替换(我尝试不成功),并且以下代码返回空文档:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(new ByteArrayInputStream(xmlStr.getBytes("UTF-8")));
我尝试用以下方式替换文档:
Document document = builder.parse(new InputSource(new StringReader(xmlStr)));//This used to work 2 weeks ago.
文档一直在返回空文档,我无法弄清楚自己在做什么错。几周前曾经使用过相同的代码。
我正在使用Java 1.8 !!
我请你帮忙。
更新:
这是采用上述xmlStr并尝试访问员工年龄的完整代码。
private String getElementValue(String tagName, String xmlString) { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(new InputSource(new StringReader(xmlString))); Element rootElement = document.getDocumentElement(); NodeList list = rootElement.getElementsByTagName(tagName); if (list != null && list.getLength() > 0) { NodeList subList = list.item(0).getChildNodes(); if (subList != null && subList.getLength() > 0) { return subList.item(0).getNodeValue(); } } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
根据注释,文档根本不是null,但是访问所需的xml标记存在问题。因此,代码的NodeList list = rootElement.getElementsByTagName("age");
大小为0。也就是说,它根本没有进入循环。
它似乎工作正常。在后面添加的以下代码builder.parse
表明正在解析XML:
System.out.println("Root element: " + document.getDocumentElement().getNodeName()); NodeList nodeList = document.getElementsByTagName("parameter"); for (int temp = 0; temp < nodeList.getLength(); temp++) { org.w3c.dom.Node node = nodeList.item(temp); System.out.println("\nCurrent element: " + node.getNodeName()); if (node.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) { Element element = (Element) node; System.out.println("Name: " + element.getElementsByTagName("name").item(0).getTextContent()); System.out.println("Key Value: " + element.getElementsByTagName("keyvalue").item(0).getTextContent()); } }
输出:
Root element: parameters Current element: parameter Name: emp Key Value: John Smith Current element: parameter Name: age Key Value: 22 Current element: parameter Name: Birth Date Key Value: 02/05/1978 Current element: parameter Name: password Key Value: ye63633