Reputation: 1081
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.
Upvotes: 3
Views: 3621
Reputation: 149047
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
Upvotes: 5
Reputation: 42060
You can start with:
ByteArrayInputStream inputStream =
new ByteArrayInputStream(response.getBody().getBytes("UTF-8"));
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document doc = builder.parse(new InputSource(inputStream));
You can see an example in http://www.java2s.com/Code/Java/XML/XMLDocumentinformationbyDOM.htm
Upvotes: 2
Reputation: 308988
Use a SAX or DOM parser that's built into Java. Parse the String into a DOM tree, walk the tree, get your values.
http://java.sun.com/xml/tutorial_intro.html
Upvotes: 1