问题描述:

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).

product.getClass().getDeclaredField(elementName).set(product, elementValue);

But I stand by others who have suggested XStream. It's a much cleaner way to parse XML files.

网友答案:

Java knows a lot frameworks for XML processing. Also some libs for serializing/deserializing objects to/from xml. I would recommend to have a look at JAXB.

网友答案:

Another option would be to use something like XStream to serialize/deserialize your entities to and from xml.

网友答案:

Checkout BeanUtils.setProperty

http://commons.apache.org/beanutils/

网友答案:

Hmm, perhaps not the best solution but you could also simply use a map:

public Product extends Model { 
  public Map<String,String> myMap = new HashMap<String,String>();
}

and:

public void parseElement(String elementName, String elementValue) {
   product.myMap.put(elementName,elementValue);
}  
相关阅读:
Top