使用 DOM 解析 xml,DOCTYPE 被擦除
为什么 dom 与 java 在编辑 xml 时会擦除文档类型?
得到这个xml文件:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!DOCTYPE map[ <!ELEMENT map (station*) >
<!ATTLIST station id ID #REQUIRED> ]>
<favoris>
<station id="5">test1</station>
<station id="6">test1</station>
<station id="8">test1</station>
</favoris>
我的功能非常基本:
public static void EditStationName(int id, InputStream is, String path, String name) throws ParserConfigurationException, SAXException, IOException, TransformerFactoryConfigurationError, TransformerException{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document dom = builder.parse(is);
Element e = dom. getElementById(String.valueOf(id));
e.setTextContent(name);
// Write the DOM document to the file
Transformer xformer = TransformerFactory.newInstance().newTransformer();
FileOutputStream fos = new FileOutputStream(path);
Result result = new StreamResult(fos);
Source source = new DOMSource(dom);
xformer.setOutputProperty(
OutputKeys.STANDALONE,"yes"
);
xformer.transform(source, result);
}
它正在工作,但文档类型被删除了!我刚刚得到了整个文档,但没有doctype部分,这对我来说很重要,因为它允许我通过id检索!我们如何保留文档类型?为什么它会删除它?我尝试了许多使用输出键的解决方案,例如omImpl.createDocumentType,但这些都不起作用...
谢谢!