Question

how to extract values from below xml code using java? Here I want to extract to,from,body,thread values using java. Here total code is condider as string.

<message to="-105608156545@chat.facebook.com/Smack" 
from="-105465454665906545@chat.facebook.com" 
type="chat">
<body>sai</body>
<thread>NNLWF1</thread>
<active xmlns="http://jabber.org/protocol/chatstates" />
</message>
Was it helpful?

Solution 2

String xmlString="<message>....</message>";//above xml code
JAXBContext jc = JAXBContext.newInstance( message.class );
Unmarshaller u = jc.createUnmarshaller();
message o =(message) u.unmarshal( new StreamSource( new StringReader(xmlString ) ) );
System.out.println("------getTo-------"+o.getTo());
System.out.println("------getFrom-------"+o.getFrom());
System.out.println("------getBody-------"+o.getBody()); 
System.out.println("------getThread-------"+o.getThread());

And Bean class(message) code.

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class message {



    public message(){}

    private String to;

    @XmlAttribute 
    public String getTo() {
        return to;
    }



    public void setTo(String to) {
        this.to = to;
    }


    @XmlAttribute 
    public String getFrom() {
        return from;
    }



    public void setFrom(String from) {
        this.from = from;
    }


    @XmlElement  
    public String getBody() {
        return body;
    }



    public void setBody(String body) {
        this.body = body;
    }


    @XmlElement  
    public String getThread() {
        return thread;
    }



    public void setThread(String thread) {this.thread = thread;
    }
private String from;
    private String body;
    private String thread;



    public message(String to, String from, String body,String thread ){  
        super();  
        this.to = to;  
        this.from = from;  
        this.body = body;
        this.thread = thread;

    }  

}

OTHER TIPS

One possibility would be to use Java's in built XPath capabailities, for example...

try {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document document = db.parse(new File("Test.xml"));

    XPath xPath = XPathFactory.newInstance().newXPath();
    XPathExpression expression = xPath.compile("/message[@from]");
    Node node = (Node)expression.evaluate(document, XPathConstants.NODE);
    System.out.println("From: " + node.getAttributes().getNamedItem("from").getNodeValue());

    expression = xPath.compile("/message/body");
    node = (Node)expression.evaluate(document, XPathConstants.NODE);
    System.out.println("Body: " + node.getTextContent());

    expression = xPath.compile("/message/thread");
    node = (Node)expression.evaluate(document, XPathConstants.NODE);
    System.out.println("Thread: " + node.getTextContent());
} catch (ParserConfigurationException | SAXException | IOException | DOMException | XPathExpressionException exp) {
    exp.printStackTrace();
}

Which outputs...

From: -105465454665906545@chat.facebook.com
Body: sai
Thread: NNLWF1

Take a look at:

For more details

One way you can read your XML in java is:

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class Demo {

    public static void main(String[] args) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document document = db.parse(new File("yourFile.xml"));
        NodeList nodeList = document.getElementsByTagName("message");
        for(int x=0,size= nodeList.getLength(); x<size; x++) {
            System.out.println(nodeList.item(x).getAttributes().getNamedItem("to").getNodeValue());
        }
    }
}

Hope it helps.

Here a complete example using a data projection library:

public class DataProjection {

    public interface Message {
        @XBRead("/message/@to")
        String getTo();

        @XBRead("/message/@from")
        String getFrom();

        @XBRead("/message/body")
        String getBody();

        @XBRead("/message/thread")
        String getThread();
    }


    public static void main(String[] args) {
        String xml="<message to=\"-105608156545@chat.facebook.com/Smack\" \n" + 
                "from=\"-105465454665906545@chat.facebook.com\" \n" + 
                "type=\"chat\">\n" + 
                "<body>sai</body>\n" + 
                "<thread>NNLWF1</thread>\n" + 
                "<active xmlns=\"http://jabber.org/protocol/chatstates\" />\n" + 
                "</message>";

        Message message = new XBProjector().projectXMLString(xml, Message.class);

        System.out.println(message.getFrom());
        System.out.println(message.getTo());
        System.out.println(message.getBody());
        System.out.println(message.getThread());

    }

This program prints out:

-105465454665906545@chat.facebook.com
-105608156545@chat.facebook.com/Smack
sai
NNLWF1
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top