java中jdom讀取xml的問題 本帖最后由 peng13425 于 2012-12-28 17:11:38 编辑 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 使用 XPath //*[text()='1'] 可以得到<c02_physical_activity>1</c02_physical_activity><c03_healthy_weight>1</c03_healthy_weight> import java.io.*;import javax.xml.xpath.*;import org.w3c.dom.*;import org.xml.sax.*;public class XPathExample { public static void main(final java.lang.String[] args) { try (final FileReader reader = new FileReader("xpathexample.xml")){ XPath xpath = XPathFactory.newInstance().newXPath(); String expression = "//*[text()='1']"; InputSource source = new InputSource(reader); NodeList nodes = (NodeList) xpath.evaluate(expression, source, XPathConstants.NODESET); for(int i = 0; i < nodes.getLength(); i++){ System.out.println(nodes.item(i).getNodeName()); } } catch (final IOException | XPathExpressionException e) { System.err.println(e.getMessage()); } }}使用jdk7编译运行。 SAXBuilder bulider =new SAXBuilder(); try { Document doc=bulider.build(JDomDemo.class.getResourceAsStream("NewFile.xml")); Element root=doc.getRootElement(); List<Element> list1=root.getChildren(); for(Element e1:list1) { List<Element> list2=e1.getChildren(); for(Element e2:list2) { if(e2.getTextTrim().equals("1")) { System.out.println(e2.getName()+":"+ e2.getText()); } } } } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }这个没有Xpath,你看看吧 dom4j为什么比JDOM更高效? 两者不都是生成一颗xml文档树么? netbeans安装问题 正则的数量词的问题 获取某月的天数的方法是什么?--------------急救! 程序的打印结果是?其原理是? JDBC driver路径问题 tomcat配置的迷茫 有人问我Applet有什么用? 我怎么回答? 一个Java教师兼程序员对学生学习Java的感触 关于IBM的问题 求助,,找了很多都没人回答,求真正的大神 socket通信 数据阻塞的问题
<c02_physical_activity>1</c02_physical_activity>
<c03_healthy_weight>1</c03_healthy_weight>
import javax.xml.xpath.*;
import org.w3c.dom.*;
import org.xml.sax.*;public class XPathExample {
public static void main(final java.lang.String[] args) {
try (final FileReader reader = new FileReader("xpathexample.xml")){
XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "//*[text()='1']";
InputSource source = new InputSource(reader);
NodeList nodes = (NodeList) xpath.evaluate(expression, source, XPathConstants.NODESET); for(int i = 0; i < nodes.getLength(); i++){
System.out.println(nodes.item(i).getNodeName());
} } catch (final IOException | XPathExpressionException e) {
System.err.println(e.getMessage());
}
}
}使用jdk7编译运行。
try {
Document doc=bulider.build(JDomDemo.class.getResourceAsStream("NewFile.xml"));
Element root=doc.getRootElement();
List<Element> list1=root.getChildren();
for(Element e1:list1)
{
List<Element> list2=e1.getChildren();
for(Element e2:list2)
{
if(e2.getTextTrim().equals("1"))
{
System.out.println(e2.getName()+":"+ e2.getText());
}
}
}
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}这个没有Xpath,你看看吧