如何使用DOM(JAVA)在XML文档中添加Doctype [英] How to add Doctype in XML document using DOM (JAVA)

查看:1227
本文介绍了如何使用DOM(JAVA)在XML文档中添加Doctype的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在java中使用DOM创建了一个XML文档。我无法添加doctype。我想要像这样的doctype。

I have created a XML document using DOM in java. I am unable to add doctype. I want the doctype like this.

<!DOCTYPE IndInfo PUBLIC "EDAFileSomething" "EDAFileSomething_2_0.dtd">

这是文档创建代码。

DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();

这是变形金刚对象代码。

Here is the Transformer Object Code.

TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = null;
            try {
                transformer = transformerFactory.newTransformer();
            } catch (TransformerConfigurationException ex) {
                Logger.getLogger(Reader.class.getName()).log(Level.SEVERE, null, ex);
            }
            DOMSource source = new DOMSource(doc);
            try {

                StreamResult result = new StreamResult(System.out);
                transformer.transform(source, result);
            } catch (TransformerException ex) {
                Logger.getLogger(Reader.class.getName()).log(Level.SEVERE, null, ex);
            }

            System.out.println("File saved!");


推荐答案

您可以使用DOM构建doctype并设置doctype作为输出属性。

You can construct the doctype with the DOM and set the doctype as an output property.

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
DOMImplementation domImpl = document.getImplementation();
DocumentType doctype = domImpl.createDocumentType("doctype",
    "-//Oberon//YOUR PUBLIC DOCTYPE//EN",
    "YOURDTD.dtd");
transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, doctype.getPublicId());
transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doctype.getSystemId());
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(new File(database));
transformer.transform(source, result);

这篇关于如何使用DOM(JAVA)在XML文档中添加Doctype的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆