Reputation: 5023
I have created the following XML using JAXB classes created from an XSD. I now want to use them to parse XML. The XML elements Screens
, DBSession
and CLISession
are optional and can be used in any order.
<Test>
<Screens>
<Screen attr1="qw" attr2="ds" attr3="sdf"></Screen>
</Screens>
<DBSession attr1="sd" attr2="sdf" attr3="sdf"></DBSession>
<CLISession attr1="sdf"></CLISession>
<Screens>
<Screen attr1="qdw" attr2="dss" attr3="a"></Screen>
</Screens>
</Test>
I have a class in the file Test.java
which contains the following method:
public List<Object> getCLISessionOrDBSessionOrScreens() {
if (cliSessionOrDBSessionOrScreens == null) {
cliSessionOrDBSessionOrScreens = new ArrayList<Object>();
}
return this.cliSessionOrDBSessionOrScreens;
}
I also have the following Java classes which contains methods to get the values of the attributes.
ScreenType.java
CLISissionType.java
DBSessionType.java
Using the code below I am trying to parse the XML and am able to identify the elements cliSession
, DBSession
and Screens
and their order but I am unable to get a handle on
them to call the necessary methods in the classes ScreenType.java
, CLISissionType.java
, DBSessionType.java
. How do I edit this code to access the methods in these Java files?
JAXBContext jaxbContext = JAXBContext.newInstance("com.qa.xmlgenerator.model.generatedxmlclasses");
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
StringReader reader = new StringReader(xml);
JAXBElement<?> test = (JAXBElement<?>) unmarshaller.unmarshal(reader);
Test testInfo = (Test) test.getValue();
int numComponents = testInfo.getCLISessionOrDBSessionOrScreens().size();
for(int i= 0; i<numComponents; i++){
System.out.println(testInfo.getCLISessionOrDBSessionOrScreens().get(i));
}
This is the output from the System.out.println
in the above code:
com.q1labs.qa.xmlgenerator.model.generatedxmlclasses.ScreensType@1a8b2725
com.q1labs.qa.xmlgenerator.model.generatedxmlclasses.DBSessionType@25b6fbc0
com.q1labs.qa.xmlgenerator.model.generatedxmlclasses.CLISessionType@104a0d98
com.q1labs.qa.xmlgenerator.model.generatedxmlclasses.ScreensType@6dc27e82
Upvotes: 1
Views: 607
Reputation: 459
Try this:
if(testInfo.getCLISessionOrDBSessionOrScreens().get(i) instanceof ScreensType)
{
ScreensType screenTypeObj = (ScreensType) testInfo.getCLISessionOrDBSessionOrScreens().get(i);
screenTypeObj.callYourDesiredMethod();
}
Similarly you can call others by checking their types and casting them to suitable Class and finally calling your desired methods.
Upvotes: 1