请帮忙,关于org.w3c.dom 与xml

xaser 2003-07-21 04:55:19
刚刚开始看java和xml,对java的对象概念理解不深,但是要写一些java程序处理xml。
现在有一个xml文件,我能取到这个文件,输出了正确的信息“If you see this message, everything is okay”。但我的工作是从中取得xml中定义的数据内容,例如:<email>dfd@dsfk.dfd</email>。我知道email这个element的name,那么我怎么取得其数据呢?
实在是新手,时间又比较紧,来不及自己看书研究了。希望能得到帮助,有完整的例程给我看看,谢谢了。

final String url = "e:\\download\\00TH000200303261.xml";
com.ibm.xml.parsers.DOMParser parser = new com.ibm.xml.parsers.DOMParser();
parser.parse(url);
org.w3c.dom.Document dom = parser.getDocument();
if (dom!=null)
{
out.println("If you see this message, everything is okay!");
}else {
out.println("If you see this message, it is not working");
}
...全文
78 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
sunal 2003-07-21
  • 打赏
  • 举报
回复
com.ibm.xml.parsers.DOMParser parser = new com.ibm.xml.parsers.DOMParser();
parser.parse(url);
org.w3c.dom.Document dom = parser.getDocument();
org.w3c.dom.NodeList nodelist = dom.getElementsByTagName("email");
org.w3c.dom.Node node = nodelist.item(0);
org.w3c.dom.Node childnode = node.getFirstChild();

if (dom!=null)
{
out.println(childnode.getNodeValue());
}else {
out.println("If you see this message, it is not working");
}

必须取得textnode 才能取得值,一开始你取到的nodetype为elementnode
xaser 2003-07-21
  • 打赏
  • 举报
回复
好了,终于自己弄清楚了,还要对node取childenode,用childnode.getnodevalue()才能取到值
xaser 2003-07-21
  • 打赏
  • 举报
回复
final String url = "e:\\xht\\download\\00TH000200303261.xml";
com.ibm.xml.parsers.DOMParser parser = new com.ibm.xml.parsers.DOMParser();
parser.parse(url);
org.w3c.dom.Document dom = parser.getDocument();
org.w3c.dom.NodeList nodelist = dom.getElementsByTagName("email");
org.w3c.dom.Node node = nodelist.item(0);
out.println(node.getNodeValue());

现在改成这样,能取到nodelist.getLength() 为 1
但node.getNodeValue()总是为null
xaser 2003-07-21
  • 打赏
  • 举报
回复
不好意思,好像org.w3c.dom 这个包中的document对象没有 getRootElement()这个method啊,你这个doc 是怎么定义的?
luckyfanjian 2003-07-21
  • 打赏
  • 举报
回复
Element root = doc.getRootElement(); //得到根元素

java.util.List books = root.getChildren(); //得到根元素所有子元素的集合

Element book = (Element)books.get(0); //得到第一个book元素

//为第一本书添加一条属性

Attribute a = new Attribute("hot","true");

book.setAttribute(a);

Element author = book.getChild("author"); //得到指定的字元素

author.setText("王五"); //将作者改为王五

//或 Text t = new Text("王五");book.addContent(t);

Element price = book.getChild("price"); //得到指定的字元素

//修改价格,比较郁闷的是我们必须自己转换数据类型,而这正是JAXB的优势

author.setText(Float.toString(50.0f));







String indent = " ";

boolean newLines = true;

XMLOutputter outp = new XMLOutputter(indent,newLines,"GBK");

outp.output(doc, new FileOutputStream("exampleB.xml"));

67,512

社区成员

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

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