从XML过滤格式化文本节点

时间:2010-10-27 20:40:29

标签: java xml

我的代码创建了一个难以在基本文本编辑器中阅读的XML文档。我尝试使用transformer.setOutputProperty(OutputKeys.INDENT, "yes")这是更好的,但现在当我读回XML时,我有所有这些烦人的文本节点,以前没有。所有这些文本节点都包含换行符“\ n”。当我读回XML而不必编写代码来解析并自行删除它时,有没有办法排除它们?某种过滤器可能吗?

修改

我检查了丹尼尔对setIgnoringElementContentWhitespace(true)的建议,但遇到了两个问题:

  1. 我必须将DOMBuilderFactory置于验证模式
  2. 验证模式需要DTD - 我没有DTD,我创建的程序允许用户动态创建新标签...
  3. 所以为了使事情复杂化,有没有办法在没有DTD的情况下做到这一点?或者在保存XML文件时是否有一种简单的方法来创建DTD?

2 个答案:

答案 0 :(得分:0)

XSL Transform可以解决问题,这正是XSL的用途。处理XML文件以不同的格式呈现它们。过滤掉有问题的节点并通过不变的方式传递其他所有内容非常简单。

无论你做什么, NOT 尝试使用正则表达式解析XML,XML不是regular language,追求正则表达式来解析XML是一条通向{{{ 3}},以及更糟糕的漏洞脆弱的代码。

答案 1 :(得分:0)

AFAIK大多数XML解析器都有跳过空文本节点的选项,就像它们总是会出现一样。至少,Xerces确实如此。该功能称为

http://apache.org/xml/features/dom/include-ignorable-whitespace

并允许禁用它(默认情况下启用它,如果我正确读取它)。说明:

True:       Includes text nodes that can be considered "ignorable whitespace" in the DOM tree. 
False:      Does not include ignorable whitespace in the DOM tree. 
Default:    true 
Note:       The only way that the parser can determine if text is ignorable
            is by reading the associated grammar and having a content model
            for the document. When ignorable whitespace text nodes are included
            in the DOM tree, they will be flagged as ignorable. The ignorable 
            flag can be queried by calling the
            TextImpl#isIgnorableWhitespace():boolean method.