当前位置: 代码迷 >> J2SE >> java dom 解析xml有关问题.多谢各位
  详细解决方案

java dom 解析xml有关问题.多谢各位

热度:453   发布时间:2016-04-24 13:34:30.0
java dom 解析xml问题.谢谢各位.
我需解析的xml文件格式如下:
<?xml version="1.0" encoding="gb2312"?>
<xmlSet>
<db name = "aaa">
<table name="test1">
<field name="id"></field>
<field name="name"></field>
<field name="age"></field>
</table>
<table name="test2">
<field name="id"></field>
<field name="name"></field>
<field name="age"></field>
</table>
</db>
<db name = "bbb">
<table name="test3">
<field name="id"></field>
<field name="name"></field>
<field name="age"></field>
</table>
<table name="test4">
<field name="id"></field>
<field name="name"></field>
<field name="age"></field>
</table>
</db>
</xmlSet>


------解决方案--------------------
存hashtable里面吧?看结构好像应该是3层的hashtable。

第一层key是db name,value是table的hashtable,第二层key是table name,value是field的hashtable,第三层key是field name,value是属性的值

public static Hashtable<String, Hashtable<String, String>> codeTable = new Hashtable<String, Hashtable<String, String>>();

public static void init(String realPath) throws ParserConfigurationException, SAXException, IOException {


DocumentBuilderFactory newFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder newBuilder = newFactory.newDocumentBuilder();
Document doc = newBuilder.parse(realPath); //realpath放xml文件的路径,可以用listener初始化
Element root = doc.getDocumentElement();
NodeList dbNode = root.getElementsByTagName("db");


for (int i = 0; i < dbNode.getLength(); i++) {
Hashtable itemTable = new Hashtable();
Element eleDb = (Element) dbNode.item(i);
codeTable.put(eleDb.getAttribute("name"), itemTable);
NodeList tableNode = eleDb.getElementsByTagName("table");
for (int j = 0; j < tableNode.getLength(); j++) {
Element eleCodeItem = (Element) tableNode.item(j);
Hashtable fieldTable = new Hashtable();
itemTable.put(eleCodeItem.getAttribute("name"), fieldTable);
NodeList fieldNode = eleCodeItem.getElementsByTagName("field");
for(int m = 0 ; m < fieldNode.getLength(); m ++){
Element eleFieldItem = (Element) fieldNode.item(m);
fieldTable.put(eleFieldItem.getAttribute("name"), value);

}
}
}

}
------解决方案--------------------
用dom4j一个外部包,很好用
  相关解决方案