如何使用java从xml代码中提取值?

时间:2014-05-07 05:32:02

标签: java xml parsing

如何使用java从xml代码中提取值? 在这里,我想使用java从body,thread,thread值中提取。 这里的总代码是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>

4 个答案:

答案 0 :(得分:1)

一种可能性是在内置的XPath功能中使用Java,例如......

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();
}

哪些输出......

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

看看:

了解更多详情

答案 1 :(得分: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());

和Bean类(消息)代码。

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;

    }  

}

答案 2 :(得分:0)

您可以在java中读取XML的一种方法是:

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());
        }
    }
}

希望它有所帮助。

答案 3 :(得分:0)

这是一个使用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());

    }

此程序打印出来:

-105465454665906545@chat.facebook.com
-105608156545@chat.facebook.com/Smack
sai
NNLWF1