【问题标题】:Why is DocType null after transformation?为什么转换后 DocType 为空?
【发布时间】:2016-12-16 12:42:33
【问题描述】:

我收到一个文档finalDocument,并希望将DocType 设置为输入文档xmlDocument。我就是这样做的:

finalDocument = icBuilder.parse(new InputSource(new ByteArrayInputStream(xmlString.getBytes("UTF-8"))));

Transformer transformer = TransformerFactory.newInstance().newTransformer();

DocumentType doctype = xmlDocument.getDoctype();

StringWriter writer = new StringWriter();

transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doctype.getSystemId());
transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, doctype.getPublicId());    

transformer.transform(new DOMSource(finalDocument), new StreamResult(writer));

但是,由于某种原因,finalDocumentDocType 未设置。我没有得到任何异常或任何东西 - 它只是 null

知道我做错了什么吗?

顺便说一句:doctype.getSystemId()doctype.getPublicId() 不为空且有效。

【问题讨论】:

  • 嗯,它有一个 DocType 开头吗?它从未在您显示的代码片段中更新。
  • @forty-2 你的意思是finalDocument?有没有关系?
  • w3c 标签的相关性如何?这似乎不是标准本身的问题,而是编程问题。
  • @tambre 对。但是 xml 标签是如何相关的,因为这只是我在使用 Java 库时遇到的问题。剩下的只是 java 标签,但这个问题与 Java 无关。但这是一个关于恰好代表 XML 对象的 Java 对象的问题,该对象在org.w3c.* 下导入。至少这就是我为标签辩护的方式。
  • 我认为使用 XML 进行标记是有意义的,因为您正在尝试做一些与 XML 相关的事情。如果你要创建一个问题,你会用图书馆创建者的名字来标记它吗?可能不是,而是您可能会使用库的名称。标记 wiki 也倾向于更多关于标准定义,但目前还不清楚。

标签: java xml doctype


【解决方案1】:

您的finalDocument 变量作为源传递给transform 方法:

void javax.xml.transform.Transformer.transform(Source xmlSource, Result outputTarget) throws TransformerException

转换的结果放在第二个参数中。因此,我希望您使用 setOutputProperty 设置的 docType 将放置在目标上,即您的 writer 对象。

【讨论】:

  • 是的 - 这就是为什么你不应该从其他地方复制和粘贴代码。 ^^
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-06
  • 1970-01-01
  • 2011-03-19
  • 2022-01-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多