java怎么通过xml节点的属性获取这个节点的值 5
<Record>
<Field name="Title" WordPos="0,4">java</Field>
<Field name="AlternativeTitle" WordPos="">21</Field>
<Field name="Creator" WordPos="">肖磊</Field>
</Record>
就是怎么通过Field 的 name属性值获取相应Field 节点的值,就是获取 java 、21、肖磊
求大哥大姐明示,写上具体的获取方法。感激不尽! 展开
创建解析器
SAXReader saxreader = new SAXReader();读取文档
Document doc = saxreader.read(new File("url"));获取根
Element root = doc.getRootElement();获取子节点
List<Element> list = root.elements();System.out.println(e.elementText("name"));
System.out.println(e.element("score").attributeValue("java"));
Reader reader = new InputStreamReader(con
.getInputStream());
SAXReader sax = new SAXReader();
// sax.setEncoding("GBK");Document document = sax.read(reader);
document.setXMLEncoding("GBK");
Element root = document.getRootElement();
// Document doc = reader.read(read);
// Element root = doc.getRootElement();
readNode(root, "");public static void readNode(Element root, String prefix) {
if (root == null) return;
// 获取属性
List<Attribute> attrs = root.attributes();
if (attrs != null && attrs.size() > 0) {
System.err.print(prefix);
for (Attribute attr : attrs) {
System.err.print(attr.getValue() + " ");
}
System.err.println();
}// 获取他的子节点
List<Element> childNodes = root.elements();
prefix += "\t";
for (Element e : childNodes) {
//输出内容
System.err.println(e.getName()+":"+e.getData());
readNode(e, prefix);
}
}
SAXReader reader = new SAXReader();
Document document = reader.read(new FileInputStream(f)); //dom4j读取
String xpath = "/Record/Field[@name='Creator']";//查询属性type='Creator'
Element element = (Element) document.selectSingleNode(xpath);//得到name=Creator的元素
System.out.println(element.getText());
SAXReader saxreader = new SAXReader();
//2. 读取文档
Document doc = saxreader.read(new File("url"));
//3. 获取根
Element root = doc.getRootElement();
//4. 获取子节点
List<Element> list = root.elements();
for(Element e : list){
System.out.println(e.elementText("name"));
System.out.println(e.element("score").attributeValue("java"));
}
2014-03-11
。。。我也知道用这个jar具体方法。。。