废话就很少说了,直接上代码,适合初学者(其实我就是刚学的)java
import java.io.File;
import java.io.IOException;domimport javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;uiimport org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;ormpublic 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();
}
}
}xml
上边是Java的方法,很通俗易懂,估计看一遍就会了,下面是xml文件对象
<?xml version="1.0" encoding="UTF-8"?>
<result>
<value>
<name>汉堡</name>
<secondname>略略略</secondname>
</value>
<value>
<name>浅浅</name>
<secondname>略略略</secondname>
</value>
</result>element
上边的【NodeList list = doc.getElementsByTagName("value");】拿的就是这个xml文件的<value>,get
同理,name和secondname也是拿的xml里面对应的值,写xml时注意写上<result>标签否则会报错(不太懂XML,反正不写就报错-- The markup in the document following the root element must be well-formed.org.xml.sax.SAXParseException,反正就是说你的格式不对)小小白就按照我这个写一遍应该就会了,对,就这样!^_^it