1. 程式人生 > >從XML文件和properties文件提取數據

從XML文件和properties文件提取數據

eva rgs src XML throw conf value tle tag

XML文檔格式內容如下

<?xml version="1.0" encoding="UTF-8"?>

<root> <field type="1" store="yes">title1</field> <field type="2" store="no">title2</field> <field type="3" store="yes">title3</field> </root> JAVA代碼如下 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 MyXml {
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
//讀取XML文件 File f = new File("E:\\workspace\\cn.harmel.lucene\\src\\1.xml"); //獲取DocumentBuilderFactory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//通過DocumentBuilder工廠產生一個DocumentBuilder DocumentBuilder builder = factory.newDocumentBuilder(); //利用DocumentBuilder產生Document Document doc = builder.parse(f); //獲取指定的標簽的集合 NodeList nl = doc.getElementsByTagName("field"); for (int i = 0; i < nl.getLength(); i++) { String fieldName=nl.item(i).getFirstChild().getNodeValue();//獲取標簽值 String fieldType=nl.item(i).getAttributes().getNamedItem("type").getNodeValue();//獲取標簽屬性值 String fieldStore=nl.item(i).getAttributes().getNamedItem("store").getNodeValue();//獲取標簽屬性值 System.out.println(fieldName+"------"+fieldType+"------"+fieldStore); } } }

從XML文件和properties文件提取數據