废话就不多说了,直接上代码,适合初学者(其实我就是刚学的)
import java.io.File;
import java.io.IOException;import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;public class TestXml {
public static void main(String[] args) {
testDOM();
}
public static void testDOM(){
File file = new File("d:/test01.xml");
try {
//定义工厂
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
builder = factory.newDocumentBuilder();
Document doc = builder.parse(file);
//其实上边就是准备工作,获取操作对象,没有为什么,就这样做(ps其实是我不懂,哈哈哈)
NodeList list = doc.getElementsByTagName("value");
for(int i=0;i<list.getLength();i++){//获取长度,遍历所有信息
System.out.println("姓名:"+doc.getElementsByTagName("name").item(i).getFirstChild().getNodeValue());
System.out.println("外号:"+doc.getElementsByTagName("secondname").item(i).getFirstChild().getNodeValue());
}
} catch (ParserConfigurationException 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();
}
}
}
上边是Java的方法,很通俗易懂,估计看一遍就会了,下面是xml文件
<?xml version="1.0" encoding="UTF-8"?>
<result>
<value>
<name>汉堡</name>
<secondname>略略略</secondname>
</value>
<value>
<name>浅浅</name>
<secondname>略略略</secondname>
</value>
</result>
上边的【NodeList list = doc.getElementsByTagName("value");】拿的就是这个xml文件的<value>,
同理,name和secondname也是拿的xml里面对应的值,写xml时注意写上<result>标签不然会报错(不太懂XML,反正不写就报错-- The markup in the document following the root element must be well-formed.org.xml.sax.SAXParseException,反正就是说你的格式不对)小小白就按照我这个写一遍应该就会了,对,就这样!^_^