MRM
MRM

Reputation: 571

java xpath parsing

Is there a way to retrieve from a XML file all the nodes that are not empty using XPath? The XML looks like this:

<workspace>
<light>
    <activeFlag>true</activeFlag>
    <ambientLight>0.0:0.0:0.0:0.0</ambientLight>
    <diffuseLight>1.0:1.0;1.0:1.0</diffuseLight>
    <specularLight>2.0:2.0:2.0:2.0</specularLight>
    <position>0.1:0.1:0.1:0.1</position>
    <spotDirection>0.2:0.2:0.2:0.2</spotDirection>
    <spotExponent>1.0</spotExponent>
    <spotCutoff>2.0</spotCutoff>
    <constantAttenuation>3.0</constantAttenuation>
    <linearAtenuation>4.0</linearAtenuation>
    <quadricAttenuation>5.0</quadricAttenuation>
</light>

<camera>
    <activeFlag>true</activeFlag>
    <position>2:2:2</position>
    <normal>1:1:1</normal>
    <direction>0:0:0</direction>
</camera>

<object>
    <material>lemn</material>
    <Lu>1</Lu>
    <Lv>2</Lv>
    <unit>metric</unit>
    <tip>tip</tip>
    <origin>1:1:1</origin>
    <normal>2:2:2</normal>
    <parent>
        <object>null</object>
    </parent>
    <leafs>
        <object>null</object>
    </leafs>
</object>

After each tag the parser "sees" another empty node that i don't need.

Upvotes: 1

Views: 202

Answers (3)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243609

You want:

//*[normalize-space()]

The expression:

//*[string-length(normalize-space(text())) > 0]

is a wrong answer. It selects all elements in the document whose first text node child's text isn't whitespace-only.

Therefore, this wouldn't select:

<p><b>Hello </b><i>World!</i></p>

although this paragraph contains quite a lot of text...

Upvotes: 0

Michael Kay
Michael Kay

Reputation: 163665

If you're using XSLT, use <xsl:strip-space elements="*"/>. If you're not, it depends what technology you are using (you haven't told us), eg. DOM, JDOM, etc.

Upvotes: 0

forty-two
forty-two

Reputation: 12817

I guess what you want is all element nodes that have an immediate text node child that does not consist solely of white space:

//*[string-length(normalize-space(text())) > 0]

Upvotes: 2

Related Questions