java查找xml中特定元素 5
<?xmlversion="1.0"?><!DOCTYPEnotesSYSTEM"code10_1.dtd"><notes><noteID="c0500103"><to>...
<?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 展开
<!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 展开
展开全部
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();
}
}
{
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();
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询