java查找xml中特定元素

<?xml version="1.0"?>
<!DOCTYPE notes SYSTEM "code10_1.dtd">
<notes>
<note ID="c0500103">
<to>1</to>
<from>2</from>
<heading>3</heading>
<body>4!</body>
</note>
<note ID="c0500208">
<to>5</to>
<from>6</from>
<heading>7</heading>
<body>8!</body>
</note>
</notes>
以上是我的xml文档,我想访问标签为body的元素,也就是4!和8!,用java怎么编写,用的是DOM

第1个回答  2013-01-23
public static void main(String[] args)
{
String xml = "<?xml version=\"1.0\"?><!DOCTYPE notes> <notes><note ID=\"c0500103\"><to>1</to><from>2</from><heading>3</heading><body>4!</body></note><note ID=\"c0500208\"><to>5</to><from>6</from><heading>7</heading><body>8!</body></note></notes> ";
System.out.println(xml);
try
{
Document document = DocumentHelper.parseText(xml);
// 通过路径获取body元素,从根节点notes开始
List<Element> bodyList = document.getRootElement().selectNodes("note/body");
Iterator<Element> it = bodyList.iterator();
while (it.hasNext())
{
Element elt = (Element) it.next();
System.out.println(elt.getText());
}
}
catch (DocumentException e)
{
e.printStackTrace();
}
}
相似回答