[英]Java+DOM: How do I convert a DOM tree without namespaces to a namespace-aware DOM tree?
I receive a Document
(DOM tree) from a certain API (not in JDK). 我从某个API(不在JDK中)收到一个
Document
(DOM树)。 Sadly, this Document
is not namespace-aware. 遗憾的是,此
Document
不支持名称空间。 As far as I know DOM, once generated, namespace-awareness can't be "added" afterwards. 据我所知DOM,一旦生成,之后就无法“添加”名称空间感知。
When converting this Document using a Transformer to a string, the XML is correct. 使用Transformer将此Document转换为字符串时,XML是正确的。 Elements have
xmlns:...
attributes and name prefixes. 元素有
xmlns:...
属性和名称前缀。 But from the DOM point of view, there are no namespaces and no prefixes. 但从DOM的角度来看,没有名称空间也没有前缀。
I need to be able to convert this Document
into a new Document
which is namespace-aware. 我需要能够将此
Document
转换为可识别名称空间的新Document
。 Yes, I could do this by just converting it to a string and back to DOM with namespaces enabled. 是的,我可以通过将其转换为字符串并返回到启用了名称空间的DOM来实现此目的。
But : nodes of the original tree have user-objects set. 但是 :原始树的节点具有用户对象集。 Converting to string and back would make a mapping of these user-objects to the new
Document
very complicated, if not impossible. 转换为字符串和返回将使这些用户对象到新
Document
的映射非常复杂,如果不是不可能的话。 So I really need a way to convert non-namespace DOM to namespace DOM. 所以我真的需要一种方法将非命名空间DOM转换为命名空间DOM。
Are there any more-or-less straightforward solutions for this? 对此有任何或多或少的简单解决方案吗?
Worst case (what I'm hoping to avoid) would be to manually iterate through old Document
tree and create new namespace-aware Node
for each old Node
. 最坏情况(就是我希望避免)将通过旧手动遍历
Document
树,并创建新的命名空间感知Node
的每个旧Node
。 Doing so, one had to manually "parse" namespace prefixes, watch out for xmlns
-attributes, and maintain a mapping between prefixes and namespace-URIs. 这样做,必须手动“解析”名称空间前缀,注意
xmlns
-attributes,并维护前缀和名称空间URI之间的映射。 Lots of things to go wrong. 有很多事情要出错。
I think you figured out that there is no easy way to do this. 我想你已经发现没有简单的方法可以做到这一点。 If you have an old-style DOM that thinks xmlns:foo="xxx" is an attribute and not a namespace declaration, there is no way to magically "upgrade" it.
如果你有一个认为xmlns的旧式DOM:foo =“xxx”是一个属性而不是命名空间声明,那么就没有办法神奇地“升级”它。 You would have to either serialize/reserialize or manually walk the tree and convert those attributes yourself.
您必须序列化/重新序列化或手动遍历树并自行转换这些属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.