Reputation: 55
I have the following XML
<data>
<name> James </name>
<age> 25 </age>
</data>
I try to set the name to a ClassA
and the age an other ClassB
.
Is possible do this with Diggester
?
Upvotes: 0
Views: 234
Reputation: 2836
Where do the instances of ClassA and ClassB come from? If they exist before you invoke the digester then you can do it using custom rules as follows:
String xml = "<data>"
+ "<name>James</name>"
+ "<age>25</age>"
+ "</data>";
final ClassA ca = new ClassA();
final ClassB cb = new ClassB();
Digester digester = new Digester();
digester.addRule("data/name", new Rule() {
@Override
public void body(String namespace, String name, String text) throws Exception {
ca.setName(text);
}
});
digester.addRule("data/age", new Rule() {
@Override
public void body(String namespace, String name, String text) throws Exception {
cb.setAge(Integer.parseInt(text));
}
});
digester.parse(new StringReader(xml));
If they are created by other parts of the XML parsing then would need to know more about the overall problem.
Cheers
Upvotes: 0
Reputation: 25018
If you want to take the XML values and store them into a class, I can suggest two options.
SAXParser
JAXB
SAXParser
is an XML parser which will deliver you data by callback methods. You can know exactly what tag is being processed now and get the data from that tag.
Second is JAXB
that is Java Architecture for XML Binding
.
Java Architecture for XML Binding (JAXB) allows Java developers to map Java classes to XML representations. JAXB provides two main features: the ability to marshal Java objects into XML and the inverse, i.e. to unmarshal XML back into Java objects
--Wikipedia
Now what remains is what suits your needs :)
Upvotes: 1