Parsing xml data in java
java, xml
Solution
You could use JAXB (JSR-222) and do the following. An implementation is included in Java SE 6.
Demo
package forum10520757;
import java.io.StringReader;
import javax.xml.bind.*;
import javax.xml.bind.annotation.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Person.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
StringReader xml = new StringReader("<person><id>QZhx_w1eEJ</id><first-name>pratap</first-name><last-name>murukutla</last-name></person>");
Person person = (Person) unmarshaller.unmarshal(xml);
System.out.println(person.id);
System.out.println(person.firstName);
System.out.println(person.lastName);
}
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
static class Person {
String id;
@XmlElement(name="first-name")
String firstName;
@XmlElement(name="last-name")
String lastName;
}
}
Output
QZhx_w1eEJ
pratap
murukutla
Problem
i have one requirement to get the data from the xml. String res; the data will be in the string res as follows. ``` <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <person> <id>QZhx_w1eEJ</id> <first-name>pratap</first-name> <last-name>murukutla</last-name> </person> ``` i have to get the id and the first-name and last-name from this data and has to be stored in the variables id,first-name,last-name how to access the xml to get those details.