需要解析node的值,网上找了十几篇文章基本上没有完全符合的样例,基本上node都是在meter节点上的。于是自己参照写了一个样例
<?xml version="1.0" encoding="UTF-8"?>
<METERS>
<METER>
<AMMETERNO NODE="电表编码"></AMMETERNO>
</METER>
<METER>
<METERNO NODE="电表编码"></METERNO>
</METER>
</METERS>
import java.io.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
public class XMLReader {
public void paseXml(String filepath) throws Exception {
try {
File f = new File("D:/jiexi2.xml");
DocumentBuilderFactory factory=DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(f);
// Element root = doc.getDocumentElement();
// NodeList nl1 = root.getElementsByTagName("AMMETERNO");
// Element e = (Element) nl1.item(0);
// String hlrId=e.getAttribute("NODE");
// System.out.println(hlrId);
//新的测试
Element element = doc.getDocumentElement();
NodeList METERs = element.getElementsByTagName("METER");
for(int i=0;i<METERs.getLength();i++){
Element bookElement = (Element) METERs.item(i);
NodeList childNodes = bookElement.getChildNodes();
for(int j=0;j<childNodes.getLength();j++){
Node node = childNodes.item(j);
if (node.getNodeType()== Node.ELEMENT_NODE){
childNodes.item(j).getAttributes();
Element c1 = (Element)childNodes.item(j);
String hlrId3=c1.getAttribute("NODE");
System.out.println(childNodes.item(j).getNodeName() +" :2");
System.out.println(hlrId3+ " :3");
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
输出结果
AMMETERNO :2
电表编码 :3
METERNO :2
电表编码 :3
<?xml version="1.0" encoding="UTF-8"?>
<METERS>
<METER>
<AMMETERNO NODE="电表编码"></AMMETERNO>
</METER>
<METER>
<METERNO NODE="电表编码"></METERNO>
</METER>
</METERS>
import java.io.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
public class XMLReader {
public void paseXml(String filepath) throws Exception {
try {
File f = new File("D:/jiexi2.xml");
DocumentBuilderFactory factory=DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(f);
// Element root = doc.getDocumentElement();
// NodeList nl1 = root.getElementsByTagName("AMMETERNO");
// Element e = (Element) nl1.item(0);
// String hlrId=e.getAttribute("NODE");
// System.out.println(hlrId);
//新的测试
Element element = doc.getDocumentElement();
NodeList METERs = element.getElementsByTagName("METER");
for(int i=0;i<METERs.getLength();i++){
Element bookElement = (Element) METERs.item(i);
NodeList childNodes = bookElement.getChildNodes();
for(int j=0;j<childNodes.getLength();j++){
Node node = childNodes.item(j);
if (node.getNodeType()== Node.ELEMENT_NODE){
childNodes.item(j).getAttributes();
Element c1 = (Element)childNodes.item(j);
String hlrId3=c1.getAttribute("NODE");
System.out.println(childNodes.item(j).getNodeName() +" :2");
System.out.println(hlrId3+ " :3");
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
输出结果
AMMETERNO :2
电表编码 :3
METERNO :2
电表编码 :3