Dom4j如何可以获取某个节点的值。(只知道该节点名称,不知道具体在哪个位置)

TheLost 2007-07-12 07:49:34
<a>
<b>
<c>test</c>
</b>
</a>
如何获取c的值,不知道c在哪个节点下。
...全文
1214 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
jihanzhong 2007-07-13
  • 打赏
  • 举报
回复
<a>
<b>
<c>test1</c>
</b>
</a>
<a>
<b>
<c>test2</c>
</b>
</a>

如果xml是这样的呢?楼主怎么办?
愤怒的小蒋 2007-07-13
  • 打赏
  • 举报
回复
http://www.java3z.com/cwbwebhome/article/article2/2378.html?id=1034
cccp21 2007-07-13
  • 打赏
  • 举报
回复
为什么不用JDom呢?
jfuncy 2007-07-13
  • 打赏
  • 举报
回复
可以使用 XPath 来实现,比较简单
先将 dom4j-1.6.jar 和 jaxen-1.1-beta-4.jar 加入到 CLASSPATH

1.xml:

<?xml version="1.0" encoding="UTF-8"?>
<root>
<a>
<b>
<c>test1</c>
</b>
</a>
<a>
<c>test2</c>
</a>
</root>

TestXpath.java:

public static void main(String[] args) throws DocumentException {
SAXReader reader = new SAXReader();
Document doc = reader.read(new File("d:\\1.xml"));
Element root = doc.getRootElement();
Element ec = (Element)root.selectSingleNode("//c"); //查找根元素下的第一个 c 节点
System.out.println(ec.getTextTrim()); //print "test1"

List ecList = root.selectNodes("//c"); //查找文档中所有的 c 节点

/*
* print
*
* test1
* test2
*
* */
for(Iterator iterator = ecList.iterator(); iterator.hasNext(); )
{
Element element = (Element)iterator.next();
System.out.println(element.getTextTrim());
}
}
lovetiger 2007-07-13
  • 打赏
  • 举报
回复
你给我分吗???我知道!!!
TheLost 2007-07-13
  • 打赏
  • 举报
回复
递归效率会不会比较低,有没其它方法。

to jihanzhong(逍遥)
如果有两个就取第一个。

67,516

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧