import java.util.List
import org.dom4j.Document
import org.dom4j.DocumentException
import org.dom4j.Element
import org.dom4j.io.SAXReader
public class XMLPaser {
public static void main(String[] args) {
paserXML()
}
public static void paserXML(){
SAXReader reader = new SAXReader()
try {
// 读取XML文件
Document doc = reader.read("NewFile.xml")
Element root = doc.getRootElement()
System.out.println(root.getName())
List<Element> param = root.elements()
for (Element element : param) {
if(element.attributeValue("name").equals("a")){
System.out.println(element.getText())
}
}
} catch (DocumentException e) {
e.printStackTrace()
}
}
}
java中不是有个读取xml文件的类吗?之间调用那类读取出来,然后用取节点的方法去取对应节点的里的值。等下给你代码。public class ReaderXml {
private static String filename = "E:\\workplace\\readerxml\\bin\\reader\\xml\\reader.xml"
// private static Config config
public static void main(String []args) throws Exception{
//这里用反射机制
DocumentBuilderFactory domfac=DocumentBuilderFactory.newInstance()
DocumentBuilder dombuilder=domfac.newDocumentBuilder()
//读取文件流
InputStream is=new FileInputStream(filename)
Document doc=dombuilder.parse(is)
Element root=doc.getDocumentElement()
//获取所有xml节点
NodeList dbinfo=root.getChildNodes()
if(dbinfo!=null){
for(int i=0i<dbinfo.getLength()i++){
//获取节点判断
Node db=dbinfo.item(i)
//如果是Hardwares节点,也就是你xml文件的最顶处的节点
if(db.getNodeName().equals("Hardwares")){
//获取第二个节点包含的所有节点
NodeList list=db.getChildNodes()
for(int y=0y<list.getLength()y++){
Node n=list.item(y)
//如果节点等于Hardware
if(n.getNodeName().equals("Hardware")){
//获取Hardware节点中的所有节点
NodeList CnodeList=n.getChildNodes()
//取出Hardware里面的所有节点
for(int k=0k<CnodeList.getLength()k++){
//取出节点
Node cn=CnodeList.item(k)
//去掉里面的#text文件节点。没用,这个不是你配置的节点,应该是xml文件隐藏的
if(!cn.getNodeName().equals("#text")){
//打印你所配置的所有节点 System.out.println("node["+k+"]="+cn.getNodeName()+" nodeValue["+k+"]="+cn.getTextContent())
}
}
}
}
}
}
}
}
}
//具体你要干嘛自己弄了!