如何使用java从xml代码中提取值? [英] how to extract values from below xml code using java?
本文介绍了如何使用java从xml代码中提取值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用java从xml代码中提取值?
这里我想使用java从body,thread,thread中提取。
这里的总代码为condider as string。
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>
推荐答案
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类(消息)代码。
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;
}
}
这篇关于如何使用java从xml代码中提取值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文