java DOM xml文件创建 - 在输出文件中没有选项卡或空格 [英] java DOM xml file create - Have no tabs or whitespaces in output file

查看:289
本文介绍了java DOM xml文件创建 - 在输出文件中没有选项卡或空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经浏览了stackoverflow上的帖子,但似乎没有任何帮助。

I already looked through the postings on stackoverflow but it seems that nothing helps.

这是什么:

            // write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute("indent-number", 2);
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        DOMSource source = new DOMSource(xmlDoc);
        StreamResult result =  new StreamResult(new File("C:\\testing.xml"));
        transformer.transform(source, result);

这是我得到的输出:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Satellite SatelliteName="" XmlFileVersion="">
<test0>
<test1>
<test2>
<test3>
<test4>
<test5>
<test6>
<test7>
<test8>
<test9/>
</test8>
</test7>
</test6>
</test5>
</test4>
</test3>
</test2>
</test1>
</test0>
</Satellite>

没有标签页或没有空格。

No tabs or no spaces.

我设置了缩进数,因为可能的java的bug,我激活了OutputKeys.INDENT。

I set the indent-number because of a possible bug of java and I activated OutputKeys.INDENT.

任何其他想法?

编辑1(在adarshr修复后):

Edit 1 (after adarshr's fix):

我现在有空格。只有第一个卫星条目被放置在不应该的第一行。

I now have white spaces. Only the first Satellite Entry is placed in the first line which shouldn't be.

<?xml version="1.0" encoding="UTF-8"?><Satellite SatelliteName="" XmlFileVersion="">
  <test0>
    <test1>
      <test2>
        <test3>
          <test4>
            <test5>
              <test6>
                <test7>
                  <test8>
                    <test9>blah</test9>
                  </test8>
                </test7>
              </test6>
            </test5>
          </test4>
        </test3>
      </test2>
    </test1>
  </test0>
  <sdjklhewlkr/>
</Satellite>

编辑2:

所以当前状态是我现在有空格,但在XML声明之后没有换行符。如何解决这个问题?

So the current state is that I now have whitespaces but I have no line feed after the XML declaration. How can I fix this?

推荐答案

尝试设置如下缩进量:

transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

这篇关于java DOM xml文件创建 - 在输出文件中没有选项卡或空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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