setNamespaceAware(true)有什么缺点吗? [英] Are there any disadvantages to setNamespaceAware(true)?

查看:239
本文介绍了setNamespaceAware(true)有什么缺点吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码在Java中解析XML文档:

I was parsing an XML document, in Java, using the following code:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Element el = db.parse(file).getDocumentElement();

但是,当解析使用名称空间的XML文档时,出现错误:

However, when parsing an XML document that uses namespaces, I get the error:

org.w3c.dom.DOMException: NAMESPACE_ERR: An attempt is made to create
or change an object in a way which is incorrect with regard to namespaces.
        at org.apache.xerces.dom.ElementNSImpl.setName(Unknown Source)

我通过添加以下行来解决此错误:

I solved this error by adding the line:

dbf.setNamespaceAware(true);

现在一切正常.

在我看来,将解析器设置为可识别名称空间将是一件很积极的事情.据我了解,它仍然可以很好地处理原始的"非命名空间文档,而没有任何缺点.

It would seem to me that setting the parser to be namespace-aware would be a purely positive thing. As far as I understand, it can still handle "vanilla" non-namespace documents just fine, without any disadvantages.

但是,如果是这种情况,那么为什么他们将其设为选项,以及为什么默认为false?

But yet, if that were the case, then why did they make it an option, and why false by default?

所以我的问题是:在我的软件中使用什么默认值是好的?我应该始终将其设置为true(因为这些API的设计者根本通过将其作为选项提供而搞砸了)还是应该在某些情况下将其保留为false,因为每个值都有其优势吗?如果是这样,false有什么优势?

So my question is: What is a good default for me to use in my software? Should I always set it to true (because the designers of these APIs messed up by offering it as an option at all) or should I leave it as false in some cases because each value has some advantages? If so, what are the advantages of false?

推荐答案

您不必创建带有解析的文档.您可以通过createDocument,createElement等创建文档.在非命名空间感知的文档中,冒号是节点名称的有效字符,因此,例如,您可以具有元素<foo:bar:baz>.

You don't have to create a document with a parse. You could create the document via createDocument, createElement etc. In a non-namespace-aware document, colons are a valid character of the node name, so you could, for instance, have an element <foo:bar:baz>.

在引入XML名称空间之前用此类元素编写的代码可以正常工作.因此,为了实现向后兼容性,在引入了对名称空间的支持后,保持代码正常工作而无需进行更改的唯一方法是默认情况下将名称空间感知设置为false,因为<foo:bar:baz>在名称空间感知文档中是不合法的.

Code written with such elements before XML namespaces were introduced would work fine. So for backward compatibility, when support for namespaces was introduced, the only way to keep that code working without changes, was to make namespace awareness false by default, because <foo:bar:baz> is not legal in a namespace aware document.

这篇关于setNamespaceAware(true)有什么缺点吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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