如何将XML(String)转换为有效的文件?

时间:2013-06-04 13:28:08

标签: java exception xpath document domxpath

我有XML作为字符串,我想将其转换为DOM文档,以便使用XPath解析它,我使用此代码将一个String元素转换为DOM元素:

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

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


        return  sXml;

    } 

但如果我想转换整个XML文件怎么办?我尝试了投射,但它没有工作,因为你无法从元素转换为文档(抛出异常):

例外:

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

守则:

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

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


        return (Document) sXml;

    } 

我也尝试了这个但是没有用:

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

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


        return  sXml;

    } 

我该怎么做才能解决这个问题?如果在XPath中有一种解析String而不是文档的方法,它也没关系。

1 个答案:

答案 0 :(得分:5)

也许使用这个

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