简体   繁体   English

如何在Java中将字符串解析为XML文档?

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

I'm trying to parse a string that contains an XML, into a Document Object in Java. 我正在尝试将包含XML的字符串解析为Java中的文档对象。 Here's the source code of the method: 这是该方法的源代码:

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;
}

What I always get as a value of the doc variable according to the debugger is 根据调试器,我总是得到的doc变量的值是

[#document: null] [#document:null]

Does anyone have a clue what is wrong? 有人知道出什么问题了吗?

Thank you for your time! 感谢您的时间!

This is normal as the debugger is invoking Document#toString() which prints [node_name: node_value] . 这是正常现象,因为调试器正在调用Document#toString() ,其中显示了[node_name: node_value] The node value of a document node is null according to the W3C spec . 根据W3C规范,文档节点的节点值为null。 If you want to print the name of the root element, you should evaluate doc.getDocumentElement().getNodeName() . 如果要打印根元素的名称,则应评估doc.getDocumentElement().getNodeName()

It would be nice if you post the XML document as well to see the structure, but this is what I do to read an XML. 如果您还发布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();

After that, you can use the doc.getElementsByTagName("Root Node"); 之后,您可以使用doc.getElementsByTagName("Root Node"); to get the root node of your XML. 获取XML的根节点。 The object has a lot of properties, like getFirstChild() or getChildNodes() depending on the strucure, Ill suggest to read this: 该对象具有很多属性,例如getFirstChild()getChildNodes()取决于结构,我建议阅读以下内容:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM