廢話就很少說了,直接上代碼,適合初學者(其實我就是剛學的)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