从XML文件和properties文件提取数据

本文介绍了一段JAVA代码,用于解析XML文档并读取其中的'field'标签及其属性'type'和'store'的值。通过使用DocumentBuilderFactory和DocumentBuilder,代码能够解析XML文件,并遍历所有'field'节点,输出每个节点的值和属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);
        }       
    }
}
 
public class ECPsUtils {

public static String resdProp(String key){
String vlaue = null;
// InputStream in = ECPsUtils.class.getClassLoader().getResourceAsStream("file.properties");
//// //读取配置文件
//// Properties prop = new Properties();
//// try {
//// prop.load(in);
//// vlaue = prop.getProperty(key);
//// } catch (IOException e) {
//// e.printStackTrace();
//// }
ResourceBundle bundle = ResourceBundle.getBundle("file");
vlaue = bundle.getString(key);
return vlaue;
}

转载于:https://www.cnblogs.com/ZTYCandy/p/10685632.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值