Parsing xml data in java

I have one requirement to get data from xml.

String res;

the data will be in the res line 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 need to get the identifier and name and surname from this data and should be stored in variable names, first name, first name,

how to access xml to get this information.

+3
source share
3 answers

You can 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
+5
source

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 at http://www.java2s.com/Code/Java/XML/XMLDocumentinformationbyDOM.htm

+2
source
+1

All Articles