Reputation: 21
My XML Structure.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<A>
<B ID="www">
<C>abcde</C>
</B>
</A>
I use Unmarshaller
.
System.out.println(c.toString()); => abcde
I want attribute information.
System.out.println(????????); => ID or count
help me please.
Upvotes: 2
Views: 185
Reputation: 148977
You could do the following
JAVA MODEL
JAXB (JSR-222) implementations require that you have an object model to convert your XML documents to.
A
import javax.xml.bind.annotation.*;
@XmlRootElement(name="A")
public class A {
private B b;
@XmlElement(name="B")
public B getB() {
return b;
}
public void setB(B b) {
this.b = b;
}
}
B
import javax.xml.bind.annotation.*;
public class B {
private String id;
private String c;
@XmlAttribute(name = "ID")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@XmlElement(name = "C")
public String getC() {
return c;
}
public void setC(String c) {
this.c = c;
}
}
DEMO CODE
Once you have your XML converted to Java objects, you can navigate your objects to get the desired data.
Demo
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(A.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum14951650/input.xml");
A a = (A) unmarshaller.unmarshal(xml);
System.out.println(a.getB().getId());
System.out.println(a.getB().getC());
}
}
Output
www
abcde
Upvotes: 2