我想使用 JAVA 动态地将样式表添加到 XML 文档中,但是我遇到了一个异常。我的代码片段如下所示:
final String xmlStr = "My XML tags in form of String here";
Document doc = convertStringToDocument(xmlStr);
String documen = addStylesheet( doc);
System.out.println(documen);
public static String addStylesheet(Document document)
{
ProcessingInstruction pi = (ProcessingInstruction)
document.createProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"my.stylesheet.xsl\"");
document.appendChild((Node) pi);
return document.toString();
}
抛出的异常是:
Exception in thread "main" java.lang.ClassCastException: com.sun.org.apache.xerces.internal.dom.ProcessingInstructionImpl cannot be cast to javax.xml.stream.events.ProcessingInstruction
at StringToDocumentToString.insertStylesheet(StringToDocumentToString.java:70)
at StringToDocumentToString.main(StringToDocumentToString.java:27)
请指导我做错了什么。谢谢