java解析XML
<?xml version="1.0" encoding="GBK"?>
<resp>
<code>1000</code>
<balance>0.855</balance>
<pkg count="0"/>
<smsPrice>0.045</smsPrice>
<voicePrice>0.03</voicePrice>
<signZH>大众</signZH><signEN>dz</signEN>
</resp>
factory = DocumentBuilderFactory.newInstance();
builder = factory.newDocumentBuilder();
doc = builder.parse(file);
} catch(ParserConfigurationException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException();
} catch (SAXException e) {
throw new RuntimeException();
}
// path開始
NodeList childs = doc.getChildNodes();
for(int i = 0; i < childs.getLength(); i++) {
Node n = childs.item(i);
Element e = (Element)n;
if(e.getNodeType() != Node.ELEMENT_NODE)
continue;
// resp
if(!"resp".equals(e.getTagName()))
continue;
// resp的子要素
NodeList paramNode = n.getChildNodes();
for(int j = 0; j < paramNode.getLength(); j++) {
Node n2 = (Node)paramNode.item(j);
if(n2.getNodeType() != Node.ELEMENT_NODE) continue;
// code
if("code".equals(n2.getNodeName())) {
code = Integer.parseInt(n2.getFirstChild().getNodeValue());
// balance
} else if("balance".equals(n2.getNodeName())) {
balance = Double.parseDouble(n2.getFirstChild().getNodeValue());
// pkg
} else if("pkg".equals(n2.getNodeName())) {
pkgCount = "0";
} else if ("smsPrice".equals(n2.getNodeName())) {
smsPrice = Double.parseDouble(n2.getFirstChild().getNodeValue());
} else if ("voicePrice".equals(n2.getNodeName())) {
voicePrice = Double.parseDouble(n2.getFirstChild().getNodeValue());
} else if ("signZH".equals(n2.getNodeName())) {
signZH = n2.getFirstChild().getNodeValue();
} else if ("signEN".equals(n2.getNodeName())) {
signEN = n2.getFirstChild().getNodeValue();
}
}
}
}
}
说明,"C:\\EclipseSet3.6_V01\\workspace\\NewFile.xml" 为你的xml存放的路径
运行结果:
code = 1000
balance = 0.855
pkgCount = 0
smsPrice = 0.045
voicePrice = 0.03
signZH = 大众
signEN = dz
[解决办法]
哦 上面的少删除一句话
System.out.println("keyspace = " + keyspace);