Normalizing XML namespaces in a DOM document in Java?

I wonder if there is an easy way to “normalize” the XML namespace definitions in an XML document, presented as a DOM document in Java?

the reason I need to is to compare two documents that use XML namespaces.

since XML namespaces can be specified anywhere in the document (in the root element, in any of the elements), etc., two documents that are actually the same can differ significantly when viewed from the point of view of the DOM tree. for example, all namespace attributes can be defined in the root element, and others can define each namespace in the "highest" element in the hierarchy of the DOM tree, where this namespace is applicable. In fact, these can be the same documents, but comparing them with, say, XmlUnit, you will get problems with the comparison.

to provide two examples:

<root xmlns:foo="http://foo/"> <e1> <foo:e2>bar</foo:e2> </e1> </root> 

against

 <root> <e1 xmlns:foo="http://foo/"> <foo:e2>bar</foo:e2> </e1> </root> 

these documents act the same, but the XML comparison will be different.

I wonder if there is a simple or simple way to normalize namespace definitions, say, put them all in the root element?

Of course, such code itself can be written, but if it were already available, it would be better :)

+4
source share
1 answer

XOM API has Canonicalizer for this purpose. this is not a standard W3C DOM API, but maybe it does what you need.

+4
source

Source: https://habr.com/ru/post/1412005/


All Articles