Adam Adam - 2 months ago 6
Java Question

Parsing XML with structured element names

I've got some third party XML to parse in the following form. The number of tests is unbounded, but always an integer.

<tests>
<test_1>
<foo bar="baz" />
</test_1>

<test_2>
<foo bar="baz" />
</test_2>

<test_3>
<foo bar="baz" />
</test_3>
</tests>


I'm currently parsing this with XPath, but it's a lot of messing around. Is there any way of expressing this style of XML in a XSD schema and generating JAXB classes from it.

As far as I can see this is impossible, the only thing possible is the
<xs:any processContents="lax"/>
technique from
how can I define an xsd file that allows unknown (wildcard) elements?
, however this allows any content, not specifically
<test_<integer>
. I just want to confirm I'm not missing some XSD/JAXB trick?

Note I would have preferred the XML to be structured like this. I may try to convince the third-party to change.

<tests>
<test id="1">
<foo bar="baz" />
</test>

<test id="2">
<foo bar="baz" />
</test>

<test id="3">
<foo bar="baz" />
</test>
</tests>

Answer

While there are ways of dealing with elements with structured names such as numeric suffixes,

you really should fix the underlying XML design (test_1 should be test) instead.