解释XML。大侠们帮帮我
XML:<book>
<name>name</name>
<value>我的书</value>
<name>price</name>
<value>45¥</value>
</book>
java代码:
Element root = doc.getRootElement();
List<Element> element = root .elements();
for (Element node : element) {
String value = e.elementTextTrim(node.getName());
System.out.println(value);
}
遍历4次打印的结果为:
name
我的书
name
我的书。
我想把这4个值都拿出来。不知如何做,大侠们帮帮我。。谢谢了
[ 本帖最后由 hsh_1987 于 2010-11-23 22:56 编辑 ]
搜索更多相关主题的帖子:
XML 解释
----------------解决方案--------------------------------------------------------
package com.lch.test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class XMLParse {
public XMLParse(){
DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder dombulider = domfac.newDocumentBuilder();
InputStream is = new FileInputStream("D:\\workspace6\\test\\src\\com\\lch\\test\\test.xml");
Document doc = dombulider.parse(is);
Element root = doc.getDocumentElement();
NodeList books = root.getChildNodes();
if(books != null){
for(int i=0; i<books.getLength(); i++){
Node book = books.item(i);
if(book.getNodeType() == Node.ELEMENT_NODE){
for(Node node=book.getFirstChild(); node!=null; node=node.getNextSibling()){
if(node.getNodeType() == Node.ELEMENT_NODE){
if(node.getNodeName().equals("name")){
String name1=node.getFirstChild().getNodeValue();
System.out.println(name1);
}else if(node.getNodeName().equals("price")){
String price=node.getFirstChild().getNodeValue();
System.out.println(price);
}
}
}
}
}
}
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
new XMLParse();
}
}
====================================================================================
<?xml version="1.0" encoding="gb2312"?>
<books>
<book>
<name>我的书0</name>
<price>45¥</price>
</book>
<book>
<name>我的书1</name>
<price>45¥</price>
</book>
</books>
=======================================
输出结果
我的书0
45¥
我的书1
45¥
=======================================
我功力浅,你的XML文件在我看来定义有一些问题。
不嫌弃的话,你可以看看我帮你写的一个处理方法!
----------------解决方案--------------------------------------------------------