1

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="[email protected]/Smack" 
from="[email protected]" 
type="chat">
<body>sai</body>
<thread>NNLWF1</thread>
<active xmlns="http://jabber.org/protocol/chatstates" />
</message>
2
  • 1
    Use google and search for java xml parsing keywords. You'll find your answer Commented May 7, 2014 at 5:36
  • String xml="<message>....</message>";code not present in the new file Commented May 7, 2014 at 6:01

4 Answers 4

1

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: [email protected]
Body: sai
Thread: NNLWF1

Take a look at:

For more details

Sign up to request clarification or add additional context in comments.

Comments

1
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;

    }  

}

1 Comment

+1 for an interesting idea and generation of a POJO. A link to the JAXB tutorial might not go astray either ;)
0

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.

1 Comment

In that case, you wont be extracting "to" or "from" or you can just put a check if the tag is present, then proceed for fetching attributes else just fetch body by tagName---- If this is what you asked and I understood.
0

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=\"[email protected]/Smack\" \n" + 
                "from=\"[email protected]\" \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:

[email protected]
[email protected]/Smack
sai
NNLWF1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.