JAVA读取XML文件数据
2016-09-14 14:06
323 查看
XML文档内容如下:
JAVA代码如下:
运行结果如下:
<?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代码如下:
package cn.mylucene; 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); } } }
运行结果如下:
title1------1------yes title2------2------no title3------3------yes
相关文章推荐
- Spring中的ContextLoaderListener使用
- 随手笔记
- 关于如何在web.xml中配置spring
- 【Java】核心技术点之【注解】
- 用Java语言编写一个"答答租车系统"
- Java中判断字符串是否为数字和保留两位小数的方法
- Securing REST APIs With Spring Boot
- Java ConcurrentModificationException异常原因和解决方法
- ADDITIONAL CREDENTIAL SECURITY – SPRING DATA JPA + JASYPT
- Spring Data JPA的findBy函数不能对部分属性查询
- java web编程积累
- Java中的instanceof关键字
- java反射——实现程序的动态性
- 透过简单案例熟知状态模式(一)
- INTEGRATING SPRING SECURITY WITH SPRING BOOT WEB
- 基于注解的SpringMVC简单介绍
- 学习spring mvc 四
- spring boot security reference
- 【Java】 线程安全 synchronized
- 内存溢出问题java.lang.OutOfMemoryError: PermGen space