jsp中解析dom不推荐,建议在后台用DOM取好后返回给前台jsp页面显示:
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class Baidu {
public static void main(String[] args) throws Exception {
List
Map
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i) + "--" +map.get(list.get(i)));
}
}
private static String path;
static {
path = Baidu.class.getResource("/test.xml").getPath();
try {
path = URLDecoder.decode(path, "utf-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
// 得到normativeField中每项的值
public static List
Document doc = getDocument(path);
NodeList list = doc.getElementsByTagName("normativeField");
List
// 得到normativeField中每项的值加到normativeFieldList集合里
for (int i = 0; i < list.getLength(); i++) {
normativeFieldList.add(list.item(i).getTextContent());
}
return normativeFieldList;
}
public static Map
Map
Document doc = getDocument(path);
for (int i = 0; i < list.size(); i++) {
NodeList nodeListlist = doc.getElementsByTagName(list.get(i));
Element e = (Element) nodeListlist.item(0);
String value = e.getAttribute("value");
map.put(list.get(i), value);
}
return map;
}
public static Document getDocument(String path) throws Exception {
Document doc = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().parse(path);
return doc;
}
}
控制台:
ID--eye1.id
xingming--eye1.name
xingbie--eye1.sex
nianling--eye1.age
shili--eye2.eyelight
shengao--eye2.high
tizhong--eye2.wealth
guomin--
gongfeizifei--eye1.pay
lianxifangshi--eye1.telephonenumber
bingli--eye1.content1
test.xml要在工程根目录下:eye1
eye2
SAXReader reader = new SAXReader();// 实例化解析器
File file = new File("路径");
Document doc = reader.read(file);
Element root = doc.getRootElement();// 得到根节点
List childList = root.elements(); //获取所有子节点
Element rsElement = root.element("rs");//获取rs节点
//获取子节点属性名、值
List attrList = root.attributes();
for (int i = 0; i < attrList.size(); i++) {
Attribute item = (Attribute)attrList.get(i);
System.out.println(item.getName() + "=" + item.getValue());
}
SAXReader reader = new SAXReader();// 实例化解析器
File file = new File("路径");
Document doc = reader.read(file);
Element root = doc.getRootElement();// 得到根节点
其他的,自己去参考吧,不是太难,相信你可以的!
期待大侠的回答