Xml Document Object返回null,但并非总是如此

时间:2018-02-28 08:53:02

标签: java xml io xml-parsing

我最近一直试图从xml文件中读取。我相信我正确解析但它返回null,但并不总是。我收到了我想要100次执行中的1次输入,代码没有大的改动。这是接收xml文件的文件路径的代码(也是文件在代码中)

public Document getXmlDoc(String filePath) {
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    Document doc = null;
    try {
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        doc = dBuilder.parse(new File(filePath));
        doc.getDocumentElement().normalize();
        System.out.println(doc.getDocumentElement().getNodeValue());//null
        System.out.println(doc.getDocumentElement().getChildNodes().item(1));//null
        System.out.println(doc.getDocumentElement().getLastChild().getAttributes().getNamedItem("id"));//not null and correct
        System.out.println(doc.getDocumentElement().getElementsByTagName("entry").item(1));//null
    } catch (ParserConfigurationException e) {
        e.printStackTrace();//pipe these
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return doc;
}

此外,我在此处调用我的方法并将我的节点转换为字符串

  NodeList nList = getXmlDoc(newFilePath).getElementsByTagName("entry");
System.out.println(nodeToString(nList.item(i)));

其中nList是节点列表,nodeToString方法是这样的:

private String nodeToString(Node node){
    StringWriter sw = new StringWriter();
    try{
        Transformer t = TransformerFactory.newInstance().newTransformer();
        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes");
        t.transform(new DOMSource(node),new StreamResult(sw));
    } catch (TransformerException e) {
        e.printStackTrace();
    }
    return sw.toString();
}

0 个答案:

没有答案