DOM XML Public Doctype未出现在result xml文件中

时间:2017-07-04 07:38:23

标签: java xml dom

我编写了一个生成XML文件的代码。我坚持为XML定义doctype,因为它应该是公开的。我能够成功获得SYSTEM doctype,但不知何故无法获得用XML编写的公共doctype。下面的SYSTEM doctype代码正在运行,但PUBLIC doctype的相同代码段不起作用:

String xmldestpath = "C:/failed/tester.xml";
        doctype2 = CreateDoctypeString();

        StreamResult result =  new StreamResult(new File(xmldestpath ));
          try {
              transformer = transformerFactory.newTransformer();
              transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"TEST");
              transformer.transform(source, result);
    //        logger.debug("COMPLETED Copying xml files /....!!");            

            System.out.println("COMPLETED Copying xml files to bulk import....!!");

不工作的代码段。它没有给出错误但是在结果xml中没有出现doctype:

 String xmldestpath = "C:/failed/tester.xml";
    doctype2 = CreateDoctypeString();

    StreamResult result =  new StreamResult(new File(xmldestpath ));
      try {
          transformer = transformerFactory.newTransformer();
          transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC,"TEST");
          transformer.transform(source, result);
//        //logger.debug("COMPLETED Copying xml files /....!!");              

        System.out.println("COMPLETED Copying xml files to bulk import....!!");

1 个答案:

答案 0 :(得分:0)

如果你知道你需要/想要PUBLIC,也许你应该知道没有系统文字就不能存在公共文字。

XML specification显示:

ExternalID  ::=  'SYSTEM' S SystemLiteral
                 | 'PUBLIC' S PubidLiteral S SystemLiteral

因此,应该很容易得出结论,您需要指定两者才能使其正常工作,如MCVE所示:

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "TEST1");
transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "TEST2");
transformer.transform(new StreamSource(new StringReader("<Root></Root>")),
                      new StreamResult(System.out));

输出

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE Root PUBLIC "TEST1" "TEST2">
<Root/>