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

前端 未结 4 1353
暗喜
暗喜 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:51

    This works for me in Java 1.5 - I stripped out specific exceptions for readability.

    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.DocumentBuilder;
    import org.w3c.dom.Document;
    import java.io.ByteArrayInputStream;
    
    public Document loadXMLFromString(String xml) throws Exception
    {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
    
        return builder.parse(new ByteArrayInputStream(xml.getBytes()));
    }
    

提交回复
热议问题