Alex Worden
Alex Worden

Reputation: 3415

How do I find all xml elements of a specific type using xpath?

I have an XSD that defines a complexType (say 'FooType'), and several named instances of this type scattered throughout the same XSD, like:

<sequence>
    <element name="A" type="tns:FooType"/>
    <element name="B" type="tns:FooType"/>
</sequence>

When working with an XML file derived from the XSD, I want to find all element nodes that of the type "tns:FooType". I think this is possible using XPath with the element(*, "FooType) method, but I can't find any examples of this so don't know what the syntax would look like. I'm hoping to use this with the Java dom4j selectNodes() method.

Upvotes: 1

Views: 453

Answers (3)

Jens Erat
Jens Erat

Reputation: 38682

If you do not know the prefix you could use substring-before() on the name and check if there is a result:

/sequence/element[substring-before(@type,":FooType")]

Upvotes: 0

forty-two
forty-two

Reputation: 12817

You need an XPath 2.0 implementation. DOM4J is 1.0 only, and so is javax.xml.xpath. Saxon provides 2.0, but I believe this specific capability is not part of the open source edition.

Upvotes: 1

surfealokesea
surfealokesea

Reputation: 5116

Try this:

List list = document.selectNodes( "/sequence/element[@type='tns:FooType']" );

Upvotes: 0

Related Questions