What does Java Node normalize method do?

Tom Brito picture Tom Brito · Mar 16, 2010 · Viewed 21.4k times · Source

I'm doing some tests, but I see no difference when I use or not the normalize() method. But the examples at ExampleDepot website use it. So, what is it for? (The documentation wasn't clear for me either)

Answer

Michael Borgwardt picture Michael Borgwardt · Mar 16, 2010

You can programmatically build a DOM tree that has extraneous structure not corresponding to actual XML structures - specifically things like multiple nodes of type text next to each other, or empty nodes of type text. The normalize() method removes these, i.e. it combines adjacent text nodes and removes empty ones.

This can be useful when you have other code that expects DOM trees to always look like something built from an actual XML document.

This basically means that the following XML element

<foo>hello 
wor
ld</foo>

could be represented like this in a denormalized node:

Element foo
    Text node: ""
    Text node: "Hello "
    Text node: "wor"
    Text node: "ld"

When normalized, the node will look like this

Element foo
    Text node: "Hello world"