简体   繁体   English

如何将XML(字符串)转换为有效文档?

[英]How to convert XML (String) to a valid document?

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: 我将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;

    } 

but what if i want to convert a whole XML file?? 但是如果我想转换整个XML文件呢? i tried casting but it didn't work as you can't convert from Element to a Document(Exception thrown): 我尝试了强制转换,但是由于您无法从Element转换为Document(抛出异常)而无法正常工作:

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. 并且如果XPath中有一种方法可以解析String而不是文档,那么也可以。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM