问题描述
我将XML作为字符串,我想将其转换为DOM文档以便使用XPath进行解析,我使用此代码将一个String元素转换为DOM元素:
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;
}
但是如果我要转换整个XML文件怎么办? ?我尝试了强制转换,但由于您无法从Element转换为Document(抛出异常)而无法正常工作:
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):
异常:
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;
}
我也尝试过这种方法,但是没有用:
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,并且在XPath中解析字符串而不是文档来解决问题。此
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)));
}
这篇关于如何将XML(字符串)转换为有效文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!