【发布时间】:2011-07-09 19:42:34
【问题描述】:
为什么 dom with java 在编辑 xml 时会删除 doctype?
得到这个 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 检索! 我们如何保留文档类型?为什么要删除它? 我尝试了许多使用 outputkeys 或 omImpl.createDocumentType 的解决方案,但这些都不起作用......
谢谢!
【问题讨论】:
-
我很惊讶你得到了什么;您的 XML 无效。
-
两件事:1)您的文档类型(地图)与您的根元素(收藏夹)不匹配。 2) 未声明元素“站”。您应该为站添加一个元素声明,然后将“favoris”更改为“map”(或更改文档类型和元素声明)。
-
对不起,你能写在这里吗?因为我对文档类型的东西完全陌生... :=)
-
可能是这样的? ]>