簡體   English   中英

如何在Java中將字符串解析為XML文檔?

[英]How can I parse a String into an XML Document in Java?

我正在嘗試將包含XML的字符串解析為Java中的文檔對象。 這是該方法的源代碼:

private Document getDocument(String xml) {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
    DocumentBuilder builder = null;  

    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }

    Document doc = null;
    try {
        doc = builder.parse(new InputSource(new StringReader(xml)));
    } catch (SAXException e) {
        System.out.println(e.toString());
    } catch (IOException e) {
        System.out.println(e.toString());
    }

    return doc;
}

根據調試器,我總是得到的doc變量的值是

[#document:null]

有人知道出什么問題了嗎?

感謝您的時間!

這是正常現象,因為調試器正在調用Document#toString() ,其中顯示了[node_name: node_value] 根據W3C規范,文檔節點的節點值為null。 如果要打印根元素的名稱,則應評估doc.getDocumentElement().getNodeName()

如果您還發布XML文檔以查看其結構,那將是很好的,但這就是我讀取XML的工作。

    // Opening and creating file Objects
    File inputFile = new File(xmlFile);
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(inputFile);
    doc.getDocumentElement().normalize();

之后,您可以使用doc.getElementsByTagName("Root Node"); 獲取XML的根節點。 該對象具有很多屬性,例如getFirstChild()getChildNodes()取決於結構,我建議閱讀以下內容:

http://www.w3schools.com/xml/dom_intro.asp

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM