How to convert XML (String) to a valid document?

≡放荡痞女 提交于 2019-12-10 11:48:42

问题


I have XML as a string and i want to convert it to DOM document in order to parse it using XPath, i use this code to convert one String element to DOM element:

public Element convert(String xml) throws ParserConfigurationException, SAXException, IOException{

        Element sXml =  DocumentBuilderFactory
                .newInstance()
                .newDocumentBuilder()
                .parse(new ByteArrayInputStream(xml.getBytes()))
                .getDocumentElement();


        return  sXml;

    } 

but what if i want to convert a whole XML file?? i tried casting but it didn't work as you can't convert from Element to a Document(Exception thrown):

The Exception :

Exception in thread "main" java.lang.ClassCastException: com.sun.org.apache.xerces.internal.dom.DeferredElementImpl cannot be cast to org.w3c.dom.Document

The Code :

public Document convert(String xml) throws ParserConfigurationException, SAXException, IOException{

        Element sXml =  DocumentBuilderFactory
                .newInstance()
                .newDocumentBuilder()
                .parse(new ByteArrayInputStream(xml.getBytes()))
                .getDocumentElement();


        return (Document) sXml;

    } 

i also tried this but didn't work:

public Document convert(String xml) throws ParserConfigurationException, SAXException, IOException{

        Document sXml =  DocumentBuilderFactory
                .newInstance()
                .newDocumentBuilder()
                .parse(new ByteArrayInputStream(xml.getBytes()));


        return  sXml;

    } 

what can i do to fix this problem? and if there is a way in XPath to parse a String rather than a document it also will be fine.


回答1:


Maybe by using this

public static Document stringToDocument(final String xmlSource)   
    throws SAXException, ParserConfigurationException, IOException {  
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
    DocumentBuilder builder = factory.newDocumentBuilder();  

    return builder.parse(new InputSource(new StringReader(xmlSource)));  
}  


来源:https://stackoverflow.com/questions/16919169/how-to-convert-xml-string-to-a-valid-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!