私は文字列として XML を持っており、XPath を使用して解析するためにそれを DOM ドキュメントに変換したいと考えています。このコードを使用して、1 つの文字列要素を 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 にあれば、それも問題ありません。