java读XML的问题,不是很难,进来留言都有分,分不够再加

bbbxx 2005-03-10 12:30:31
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;

public class useDomPrintElements {
public static NodeList nodelist;
public static void main(String[] args) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new File("publication.xml"));
Element element = document.getDocumentElement();
nodelist = element.getChildNodes();
System.out.println(nodelist.getLength());
for(int i=0;i<nodelist.getLength();i++) {
Node m=nodelist.item(i);
System.out.println(m.getNodeName());
}
}
catch(Exception e){}
}
------------------------------------------------------------------publication.xml
<?xml version="1.0" encoding="UTF-8"?>
<publication>
<book>
<Title>The Mythical Man-month</Title>
<Writer>Frederick P. Brooks Jr.</Writer>
<PublishDate>1975-03-12</PublishDate>
</book>
<book>
<Title>Think In Java</Title>
<Writer>Bruce Eckel</Writer>
<PublishDate>1999-04-01</PublishDate>
</book>
</publication>
--------------------------------------------------------------问题1
for循环打出的为什么是
#text
book
#text
book
#text

--------------------------------------------------------------问题2
根接点下明明只有2个<book></book>为什么会循环5次呢?#text是什么东西呀?
...全文
123 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
shangwei80 2005-03-10
  • 打赏
  • 举报
回复
Element node=(Element)nl.item(i);改为:
Element node=(Element)nodelist.item(i);
shangwei80 2005-03-10
  • 打赏
  • 举报
回复
for(int i=0;i<nodelist.getLength();i++)
{
Element node=(Element)nl.item(i);
System.out.println("Title:"+node.getElementsByTagName("Title").item(0).getFirstChild().getNodeValue());
System.out.println("Writer:"+node.getElementsByTagName("Writer").item(0).getFirstChild().getNodeValue());
System.out.println("PublishDate:"+node.getElementsByTagName("PublishDate").item(0).getFirstChild().getNodeValue());
}
shihp 2005-03-10
  • 打赏
  • 举报
回复
你看一下JDK的文档,就知道了
rootcn 2005-03-10
  • 打赏
  • 举报
回复
#text 是文本类型, 用 getNodeName() 取得,如果用getNodeValue()就能取到它的值了.
rootcn 2005-03-10
  • 打赏
  • 举报
回复
文档中说,元素之间的空格也算是一个text 元素.
如果你将XML改为以下,就只有两个了.
-----------------
publication.xml
<?xml version="1.0" encoding="UTF-8"?>
<publication><book>
<Title>The Mythical Man-month</Title>
<Writer>Frederick P. Brooks Jr.</Writer>
<PublishDate>1975-03-12</PublishDate>
</book><book>
<Title>Think In Java</Title>
<Writer>Bruce Eckel</Writer>
<PublishDate>1999-04-01</PublishDate>
</book></publication>

67,512

社区成员

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

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