您的位置:首页 > 编程语言 > Java开发

java解析xml文件获取xml里面的信息

2014-02-17 11:03 501 查看
<?xml version="1.0"?>
<InvokeReturn xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Success>true</Success>
<Time>2014-02-07T10:05:11.1613672+08:00</Time>
<Object xsi:type="TerminalModel">
<TerminalId>860806025604744</TerminalId>
<TerminalName>HTC</TerminalName>
</Object>
</InvokeReturn>

要是想解析上面xml里面的信息:使用的dom4j.jar包!!!

下面是我自己写的方法!测试后没问题!

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

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

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class TTPP {

public  TTPP() throws ParserConfigurationException, SAXException, IOException{
DocumentBuilderFactory domfac=DocumentBuilderFactory.newInstance();
DocumentBuilder dombuilder=domfac.newDocumentBuilder();
InputStream is=new FileInputStream("/1.xml");
Document doc=dombuilder.parse(is);
Element root=doc.getDocumentElement();
NodeList books=root.getChildNodes();
if(books!=null){
for(int i=0;i<books.getLength();i++){
Node book=books.item(i);
int p=0;//用来控制读取object标签时循环多次的问题
for(Node node=book.getFirstChild();node!=null;node=node.getNextSibling()){//循环读取出xml里面的内容
if(book.getNodeName().equals("Success")){
String success=book.getFirstChild().getNodeValue();
System.out.println("Success:"+success);
}
if(book.getNodeName().equals("Time")){
String time=book.getFirstChild().getNodeValue();
System.out.println(time);
}
if(book.getNodeName().equals("Object")){
if(p==0){
System.out.println("ceshi:"+book.getAttributes().getNamedItem("xsi:type").getNodeValue());//当前的标签
NodeList nl=book.getChildNodes();
for(int j=0;j<nl.getLength();j++){
Node childNode = (Node) nl.item(j);
if (childNode.getNodeType() == Node.ELEMENT_NODE){
Element childElement = (Element) childNode;
String attrA = childElement.getTextContent();
System.out.println("what:"+attrA);
//版本号
if ("TerminalId".equals(childElement.getNodeName())){
System.out.println(childElement.getFirstChild().getNodeValue());
}
if("TerminalName".equals(childElement.getNodeName())){
System.out.println(childElement.getFirstChild().getNodeValue());
}
if("s".equals(childElement.getNodeName())){
System.out.println(childElement.getFirstChild().getNodeValue());
}
if("ss".equals(childElement.getNodeName())){
System.out.println(childElement.getFirstChild().getNodeValue());
}
}
}
}
p=1;
}

}
}
}
}
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
new TTPP();
}
}
输出的内容为:

Success:true
2014-02-07T10:05:11.1613672+08:00
ceshi:TerminalModel
what:860806025604744
860806025604744
what:HTC
HTC
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  标签 测试 xsd xml 关键字