java - 添加 xml-stylesheet 并获得 standalone = yes

标签 java xml xslt

我在下面的代码中添加了解决方案。

底部的代码是我的。我删除了所有标签的创建。

在我得到的 xml 文件的顶部。 <?xml version="1.0" encoding="UTF-8" standalone="no"?>请注意,standalone 是 no,即使你已将其设置为 yes。

第一个问题:如何获取standalone = yes?

我想添加<?xml-stylesheet type="text/xsl" href="my.stylesheet.xsl"?>在 xml 文件的第二行。

第二个问题:我该怎么做?

一些有用的链接?有什么事吗?

DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();  
DocumentBuilder docBuilder = dbfac.newDocumentBuilder();  
Document doc = docBuilder.newDocument();
doc.setXmlStandalone(true);
ProcessingInstruction pi = doc.createProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"my.stylesheet.xsl\"");

Element root = doc.createElement("root-element");
doc.appendChild(root);
doc.insertBefore(pi, root);    

<cut>  

TransformerFactory transfac = TransformerFactory.newInstance();
transfac.setAttribute("indent-number", new Integer(2));
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
trans.setOutputProperty(OutputKeys.STANDALONE, "yes");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
trans.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "name");

FileOutputStream fout = new FileOutputStream(filepath);
BufferedOutputStream bout= new BufferedOutputStream(fout);
trans.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(bout, "utf-8")));

最佳答案

我加了

doc.setXmlStandalone(true);
ProcessingInstruction pi = doc.createProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"my.stylesheet.xsl\"");`  

切割前

doc.insertBefore(pi, root);

在根元素被附加到文档之后。

关于java - 添加 xml-stylesheet 并获得 standalone = yes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2651647/

相关文章:

xslt - XSL :FO/Apache FOP 中的内嵌图像数据

xslt - 为什么 XSLT 似乎激怒了这么多人?

java - 如何创建一个正则表达式,仅用两个替换两个或多个连续的相同字符?

java - 单元测试依赖于另一个服务类的Spring引导服务类

java - 如果sonarqube中的主要问题数量大于50,要使我们的本地构建失败

sql-server - SQL Server XML 解析第一个节点属性

java - 为什么需要定义自定义构造函数?

php - PHP 中的容错 HTML/XML/SGML 解析

xml - XSLT 转换取决于父项值

java - 无法从 SaxonEE9-9-1-4J 中的 XSLT 调用扩展 Java 方法