I’m relatively new to Java and would appreciate any help on this!
I have an XML file full of products like this:
<product>
<title>Product Title</title>
<colour>Red</colour>
</product>
And I have a JPA Entity like this:
@Entity
public Product extends Model {
public String title;
public String colour;
}
And I can happily parse the XML into my JPA object like this:
public void parseElement(String elementName, String elementValue) {
if (elementName == "title") {
product.title = elementValue;
}
else if (elementName == "colour") {
product.colour = elementValue;
}
}
However the problem is that there are over 50 fields per product, not just the two. I could write a 50+ clause if-else statement, but thought it’d be worth checking here for better alternatives first!
As the XML element names directly match to the property names in the Product class, I thought something like this would be perfect:
public void parseElement(String elementName, String elementValue) {
product[elementName] = elementValue;
}
But Java doesn’t like that notation. Is there something else I can do that would achieve a similar result, or do I have to suck it up and write a collosal if-else statement?
Any help would be greatly appreciated.
Cheers!
You’ll have to use reflection (error handling ommitted).
But I stand by others who have suggested XStream. It’s a much cleaner way to parse XML files.