简体   繁体   English

Java xml自闭标签

[英]Java xml self-closing tags

My Java program looks like: 我的Java程序看起来像:

public static void main(String[] args) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db;
    try {
        db = dbf.newDocumentBuilder();
        Document document = db.parse(new ByteArrayInputStream("<test><test1></test1></test>".getBytes("UTF-8")));
        StringWriter stringWriter = new StringWriter();
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "no");
        transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
        transformer.transform(new DOMSource(document), new StreamResult(stringWriter));
        System.out.println(stringWriter.toString());
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (TransformerConfigurationException e) {
        e.printStackTrace();
    } catch (TransformerException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    }
}

Output is: <test><test1/></test> I want output <test><test1></test1></test> . 输出为: <test><test1/></test>我想输出<test><test1></test1></test>

Because I'm using JasperReports and html style only allow my wanted output. 因为我使用JasperReportshtml样式只允许我想要的输出。 How to achieve that? 怎么实现呢? Is there any output property of Transformer or any property of DocumentBuilderFactory to do wanted output? Transformer的任何输出属性或DocumentBuilderFactory的任何属性是否需要输出?

如果在调用transformer.transform之前添加此行 - 输出将采用html样式:

transformer.setOutputProperty(OutputKeys.METHOD, "html");

A way to make Java's Transformer write full closing tags is to make little changes to the Document. 使Java的Transformer编写完整结束标记的一种方法是对Document进行少量更改。 In my case, I build the DOM myself (instead of parsing an XML from String). 在我的例子中,我自己构建DOM(而不是从String解析XML)。 For each node of which I know it will make a self-closing tag, I have to (unfortunately) add a textNode with some random content of which you know it will certainly not occur in the content itself. 对于我知道它将生成一个自动关闭标记的每个节点,我不得不(不幸的是)添加一个textNode,其中包含一些随机内容,您知道它们肯定不会出现在内容本身中。 This is what I do for elements to which I don't add any other child (and thus would become a self-closing tag): 这就是我为那些我没有添加任何其他孩子的元素所做的事情(因此会成为一个自我关闭的标签):

DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element test = doc.createElement("test");
doc.appendChild(root);
Element element = doc.createElement("test1");
element.appendChild("_plchldr_"); // because we know it doesn't have children

In case of an existing Document, you would have to traverse it to find elements that don't have children. 如果是现有文档,则必须遍历它以查找没有子项的元素。 Add these same placeholders to them. 将这些相同的占位符添加到它们。

Later, when streaming this XML to our Writer, these placeholders have to be removed from the generated XML: 稍后,当将此XML流式传输到Writer时,必须从生成的XML中删除这些占位符:

TransformerFactory factory = TransformerFactory.newInstance();
transformer.setOutputProperty("omit-xml-declaration", "yes");
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
// and here's the trick:
System.out.println( sw.toString().replaceAll("_plchldr_", "") );

Alternatively you could use a wrapping Writer that removes "_plchldr_" streaming. 或者,您可以使用包装Writer删除“_plchldr_”流。 Considered the size of my XMLs (<4KB) I didn't bother writing one. 考虑到我的XML大小(<4KB),我没有费心去写一个。

Another alternative, if you don't want to go with replacing text from the output, you could add a comment instead of a text node: 另一种方法是,如果您不想从输出中替换文本,则可以添加注释而不是文本节点:

element.appendChild(doc.createComment(" "));

The result doesn't need those place holders to be removed to be valid XML, however, you will have pointless comments in your output. 结果不需要将那些占位符删除为有效的XML,但是,您的输出中将有无意义的注释。

I consider this as a dirty workaround, but it least it works! 我认为这是一个肮脏的解决方法,但它最不起作用!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM