问题
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