0

It is easy to parse XML in which tags name are fixed. In XStream, we can simply use @XStreamAlias("tagname") annotation. But how to parse XML in which tag name is not fixed. Suppose I have following XML :

<result>
  <result1>
     <fixed1> ... </fixed1>
     <fixed2> ... </fixed2>
  </result1>
  <result2>
    <item>
     <America>
         <name> America </name>
         <language> English </language>
     </America>
    </item>
    <item>
     <Spain>
         <name> Spain </name>
         <language> Spanish </language>
     </Spain>
    </item> 
  </result2>
</result>

Tag names America and Spain are not fixed and sometimes I may get other tag names like Germany, India, etc.

How to define pojo for tag result2 in such case? Is there a way to tell XStream to accept anything as alias name if tag name is not known before-hand?

Vivek Mangal
  • 532
  • 1
  • 8
  • 24

2 Answers2

1

if it is ok for you to get the tag from inside the tag itself (field 'name'), using Xpath, you can do:

//result2/*/name/text()

another option could be to use the whole element, like:

//result2/*

or also:

//result2/*/name()
marco
  • 671
  • 6
  • 22
  • just read this: https://stackoverflow.com/questions/2811001/how-to-read-xml-using-xpath-in-java and the rules, shortly explained here: https://www.freeformatter.com/xpath-tester.html in this last link you can also evaluate your pattern – marco Oct 10 '17 at 07:40
0

Some technologies (specifically, data binding approaches) are optimized for handling XML whose structure is known at compile time. Others (like DOM and other DOM-like tree models - JDOM, XOM etc) are designed for handling XML whose structure is not known in advance. Use the tool for the job.

XSLT and XQuery try to blend both. In their schema-aware form, they can take advantage of static structure information when it is available. But more usually they are run in "untyped" mode, where there is no a-priori knowledge of element names or structure, and everything is handled as it comes. The XSLT rule-based processing paradigm is particularly well suited to "semi-structured" XML whose content is unpredictable or variable.

Michael Kay
  • 156,231
  • 11
  • 92
  • 164