1

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.