XML注释可以到任何地方吗?
我编写了一个简单的工具,使用用户输入的查询来生成DBUnit XML数据集。我想将在XML中输入的每个查询作为注释包括在内,但是用于生成XML文件的DBUnit API不支持将注释插入到我希望的位置(在生成的数据上方),因此我倾向于将使用顶部或者底部的所有查询进行评论。
所以我的问题是:将XML放置在任一位置是否有效?例如,在XML声明上方:
<!-- Queries used: ... --> <?xml version='1.0' encoding='UTF-8'?> <dataset> ... </dataset>
或者在根节点下方:
<?xml version='1.0' encoding='UTF-8'?> <dataset> ... </dataset> <!-- Queries used: ... -->
我计划首先尝试在XML声明之上进行尝试,但是尽管有维基百科的要求,但我仍然怀疑那是否是有效的XML:
Comments can be placed anywhere in the tree, including in the text if the content of the element is text or #PCDATA.
我计划回发是否可行,但是很高兴知道它是否为正式的XML标准。
更新:有关测试结果,请参见下面的答复。
解决方案
回答
根据XML规范,格式良好的XML文档为:
document ::= prolog element Misc*
"序言"在哪里
prolog ::= XMLDecl? Misc* (doctypedecl Misc*)?
和
XMLDecl ::= '<?xml' VersionInfo EncodingDecl? SDDecl? S? '?>'
这意味着,如果要在顶部添加注释,则不能具有XML类型声明。
该规范在评论上与Wikipedia一致:
2.5 Comments [Definition: Comments may appear anywhere in a document outside other markup; in addition, they may appear within the document type declaration at places allowed by the grammar. They are not part of the document's character data; an XML processor MAY, but need not, make it possible for an application to retrieve the text of comments. For compatibility, the string "--" (double-hyphen) MUST NOT occur within comments.] Parameter entity references MUST NOT be recognized within comments.
所有这些加在一起意味着我们可以将注释放置在其他标记之外的任何地方,除非如果我们以注释开头则不能有XML声明。
但是,尽管理论上理论与实践相符,但实际上却不相符,所以我很想知道实验是如何进行的。
回答
第一个示例不是有效的XML,声明必须是XML文档中的第一件事。
但是除此之外,评论还可以去其他任何地方。
更正第一个示例:
<?xml version="1.0" encoding="UTF-8"?> <!-- Queries used: ... --> <dataset> </dataset>
回答
处理指令必须是XML内容中的第一件事(请参阅XML注释和处理指令)。以下应该工作:
<?xml version='1.0' encoding='UTF-8'?> <!-- Queries used: ... --> <dataset> ... </dataset>
回答
谢谢大家的回答!
事实证明,文件前面的注释似乎有效,但是当我深入研究DBUnit源时,是因为验证已关闭。
我确实尝试通过以下方式加载简单的文档:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(new File("/path/to/file"));
并且这失败了,因为XML声明不是第一件事(就像其他人指出的那样)。
因此,尽管DBUnit可以工作,但我更喜欢使用有效的XML,所以我将注释移到了最后(因为DBUnit生成XML声明,所以即使我愿意,也不能将注释放在其下方。 。至少是在事后没有修改XML的情况下,这样做的工作量超出了它的价值)。