How do I load an org.w3c.dom.Document from XML in a string?

前端 未结 4 1349
暗喜
暗喜 2020-11-27 11:57

I have a complete XML document in a string and would like a Document object. Google turns up all sorts of garbage. What is the simplest solution? (In Java 1.5)<

4条回答
  •  情深已故
    2020-11-27 12:31

    Just had a similar problem, except i needed a NodeList and not a Document, here's what I came up with. It's mostly the same solution as before, augmented to get the root element down as a NodeList and using erickson's suggestion of using an InputSource instead for character encoding issues.

    private String DOC_ROOT="root";
    String xml=getXmlString();
    Document xmlDoc=loadXMLFrom(xml);
    Element template=xmlDoc.getDocumentElement();
    NodeList nodes=xmlDoc.getElementsByTagName(DOC_ROOT);
    
    public static Document loadXMLFrom(String xml) throws Exception {
            InputSource is= new InputSource(new StringReader(xml));
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            DocumentBuilder builder = null;
            builder = factory.newDocumentBuilder();
            Document doc = builder.parse(is);
            return doc;
        }
    

提交回复
热议问题