Java读取XML文件中的配置

Java文件操作①——XML文件的读取 前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站,这篇文章男女通用,看懂了就去分享给你的码吧。 阅读详情

需求:

有一组映射关系,为了避免频繁改动造成不停打包更新的麻烦,需要将映射关系写进配置文件里,如果有更新,只需要更改配置文件并重启即可

我的xml:

<?xml version="1.0" encoding="UTF-8"?>
<MAPs>
	<!--test sample-->
    <map>
        <icuId>1</icuId>
        <serverIP>1.1</serverIP>
    </map>
    <map>
        <icuId>2</icuId>
        <serverIP>2.2</serverIP>
    </map>
    <map>
        <icuId>3</icuId>
        <serverIP>3.3</serverIP>
    </map>
    <map>
        <icuId>4</icuId>
        <serverIP>4.4</serverIP>
    </map>
    <map>
        <icuId>5</icuId>
        <serverIP>5.5</serverIP>
    </map>

</MAPs>

读取XML的工具类:

package com.siemens.sitracs_configtools.conf;

import com.siemens.sitracs_configtools.common.StaticCache;
import com.siemens.sitracs_configtools.model.IPMap;
import org.dom4j.Document;
import com.siemens.sitracs_configtools.util.XMLReader;
import org.dom4j.DocumentException;
import org.dom4j.Element;

import java.util.Iterator;

/**
 * @author SongShilun
 * @create 2021/5/17 11:39
 * @desc
 **/
public class XMLConfReader {

    public static void readXMLFile(){
        try {
            Document document= XMLReader.parse("src/main/resources/URLMapping.xml");
            Element rootElement = document.getRootElement();//MAPs

            for (Iterator<Element> it = rootElement.elementIterator("map"); it.hasNext();) {
                Element element = it.next();
                IPMap map=new IPMap(element);
                StaticCache.IPMappingMap.put(map.getIcuId(),map.getServerIP());
            }

            System.out.println("ipmapping--size--===="+StaticCache.IPMappingMap.size());
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }
}

其中用到的IPMap实体类:

package com.siemens.sitracs_configtools.model;

import org.dom4j.Element;
/**
 * @author SongShilun
 * @create 2021/5/17 12:32
 * @desc
 **/
public class IPMap {
    private String icuId;
    private String serverIP;

    public IPMap(){

    }

    public IPMap(Element element){
        this.icuId=element.element("icuId").getTextTrim();
        this.serverIP=element.element("serverIP").getTextTrim();
    }

    public String getIcuId() {
        return icuId;
    }

    public void setIcuId(String icuId) {
        this.icuId = icuId;
    }

    public String getServerIP() {
        return serverIP;
    }

    public void setServerIP(String serverIP) {
        this.serverIP = serverIP;
    }
}

总体步骤及原理:

  1. 先定义一个XML文件,XML文件里的标签可以自己定义;
  2. 引入以下依赖,使用dom4j读取XML文件里的标签内容
<!-- https://mvnrepository.com/artifact/dom4j/dom4j -->
        <dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>1.6.1</version>
        </dependency>
  1. 如XMLConfReader .java 代码所示,分层读取XML文件里的内容,并将单个元素封装为实体,添加get/set方法就可以对其中的元素进行读写。
JAVA读取数据库的XML配置文件. [原创]JAVA读取数据库的XML配置文件. 前言.虽然现在有HEIBERNATE开源结构做为持久层,可以很好的解决这个问题. 当然,SSH这些开源结构,也必并非人人都得学去用.我个人就喜欢自已写几个常用的类在开发时可以多次使用... 下次共享我所常用的数据库链接类.经过读取XML配置文件来方便用户随时更改数据库配置文件... 申明:以下源代码是我的研究心血,转帖请保留作者名字.为了方便JSP初... 阅读详情

相关推荐

实现读取XML配置文件 Java

在示例代码中,我们使用getElementsByTagName方法获取指定标签的元素列表,并根据索引获取具体的元素。在上面的代码中,我们首先创建了一个DocumentBuilderFactory实例,然后使用该实例创建了一个DocumentBuilder对象。接下来,我们需要创建一个Java类来实现读取XML配置文件的功能。在本文中,我们将学习如何使用Java编程语言读取XML配置文件,并提取其中的数据。通过这种方式,我们可以方便地读取并提取XML文件中的数据,实现配置文件的灵活管理和使用。

ScriptCharm的博客 243

java 读取 xml 配置文件内容

java 读取 xml 配置文件内容

myStyle的博客 2494

使用Java读取XML配置文件

使用Java读取XML配置文件

JAVA中读取XML文件中的配置信息

  在进行MIS系统开发过程中,从配置文件中读取配置信息是每一个系统必须具备的功能,例如,我们要配置读取数据库配置信息,包括驱动程序名、连接字符串,用户名,口令等信息,由于这些信息会随着用户的不同而发生改变,所以不能直接把参数写在程序中,将其写入配置文件,然后在应用程序中读取配置信息并加以使用,是一个成熟的MIS系统必须具有的基本功能。  JAVA与XML文件,可以说是软件开发的“黄金搭档”,

zmwg1的专栏 2万+

基于DPABI和SPM12的任务态fMRI分析笔记1——预处理

前言 原理简介 预处理

Sophia2023的博客 1万+

钢铁雄心4存档修改全攻略:从基础设置到高级玩法(附国家代码表)

本文详细解析《钢铁雄心4》存档修改技巧,从基础设置到高级玩法全覆盖。包括存档文件位置、格式转换、国家实力调整、国际关系修改等实用内容,并附赠国家代码表。掌握存档修改技能,解锁游戏全部潜力,实现精细参数控制,超越控制台指令的局限。

weixin_29233857的博客 1431

java访问xml配置文件

xml访问

weixin_55850954的博客 954

英飞凌 AURIX Development Studio工程移植到Hightec的方法

1. 软件简介 AURIX™ Development Studio是英飞凌针对AURIX TC2XX/TC3XX系列单片机推出了一款免费的软件,集成了iLLD库,内置Tasking compiler和Tasking Debugger,但这两个模块只能用于非商业用途,可供学习和试用。iLLD库是英飞凌为TC2XX和TC3XX Tricore系列单片机提供的底层驱动库,有完善的使用手册,和较好的移植性。 Hightec是一款可以用来开发Aurix系列单片机的编译器,有免费版,可商用,集成GCC编译器,可用UDE

weixin_42967006的博客 7133

JAVA读取xml文件中节点值

import org.w3c.dom.*; import javax.xml.parsers.*; import java.io.*; public class Parse{ //Document可以看作是XML在内存中的一个镜像,那么一旦获取这个Document 就意味着可以通过对 //内存的操作来实现对XML的操作,首先第一步获取XML相关的Document ...

白云城主的博客 1003

Unity动态创建Avatar骨骼映射

Unity Avatar骨骼映射动态创建,适配Unity通用动画,无需经过第三方建模软件,可运行时创建

Nbin_Newby的博客 1万+

HTML5+CSS3+JS小实例:焦点图波浪切换动画特效

实例:焦点图波浪切换动画特效。字体图标库:Font Awesome。技术栈:HTML+CSS+JS。

艾恩小灰灰的博客 907

java读取xml配置文件

1.配置文件的好处, xml配置文件的优点, 当改变底层配置时 不需要改变和重新编译代码,只需要在xml中更改就可以了 2.先看下项目架构 3.static的作用 static表示“全局”或者“静态”的意思,用来修饰成员变量和成员方法 可用类名直接访问(方便),当然也可以通过对象来访问(但是这是不推荐的) static final用来修饰成员变量和成员方法,可简单理解为“全局常量”! 对

观山是山 4598

fastlio2原理详解

其核心是利用IMU的高频数据(通常100-500Hz)进行状态预测(前向传播),同时利用激光雷达扫描(通常10-100Hz)作为观测来校正状态。转换了卡尔曼增益的计算公式,将对大维度观测矩阵的求逆(点云数量级)转换为对小维度状态矩阵的求逆,从而极大提升了计算效率。:利用预测出的连续IMU状态,将一帧内每个激光点根据其时间戳反向插值,统一校正到扫描结束时刻,输出无畸变的点云。收敛后,用最终的状态将本帧点云。,根据其精确的时间戳,利用前后两个IMU位姿进行插值,计算出该点采集时刻的精确位姿,再将其全部。

Studying…… 101

java:实现读取XML配置文件(附带源码)

java:实现读取XML配置文件(附带源码)

欢迎来到我的博客!这里是一个专注于计算机技术的分享平台,涵盖编程开发、算法研究、系统架构、软件工程等多个领域。无论你是初学者还是资深开发者,都能在这里找到有价值的内容。 748

《用 R 探索医药数据科学》目录(持续更新,已超 250 万字)|订阅前说明

我们重磅推出《用 R 探索医药数据科学》专栏!本文作为专栏【订阅后首读】的核心内容,堪称开启学习之旅的 “入门钥匙”,也是整个专栏最关键的一篇指引文。文中不仅完整呈现了专栏 9 大核心篇章 + 问答板块的详细目录,更囊括了订阅后必知的核心要点 —— 从阅读设备、实操工具的使用建议,到学习路径、更新规则的清晰说明,再到问题反馈、感悟记录的实用方法,一站式帮你摸清专栏框架、找准学习方向。建议各位订阅者务必认真阅读、吃透内容,这能让你后续的学习更高效、少走弯!

MD Code 1万+

1、微软 Intune 全面指南:配置、管理与自动化

本文全面介绍了微软 Intune 的配置、管理和自动化操作,涵盖用户与设备管理、安全策略设置、跨平台应用部署、合规性监控及报告分析等内容。通过详细的操作步骤、自动化脚本示例和流程优化建议,帮助技术人员高效掌握 Intune 在混合办公环境中的实际应用,并展望其未来发展趋势。

ii567的博客 356

java 读取配置xml_java读取xml-.properties配置文件

package org.ifocus.crawler.main;import java.io.BufferedInputStream;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.util.Enumeration;import java.util.It...

weixin_29775447的博客 144

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

java由JABXContext注解方式读取xml配置文件

1. 本帖内容      在用java作开发时,一般会选择使用xml文件作为配置文件,故而通过java工程读取配置文件则是必须掌握的知识;传统的C/C++通过File文件的方式或者说通过流的方式进行读写,过分的浪费内存与效率,且读写及其不方便,不适用于java的灵活配置,而java的注解方式成功的解决了该问题。       作者在从事相关的开发中学习了一下注解的方式,并成功开发了项目;虽然现在网上...

beitian_123的博客 1489

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

java读取xml配置_Java读取XML配置文件

最初的想法是不把mysql的连接参数写到程序中,因为每次要修改参数总是很麻烦,于是想找到一种能够方便修改的方式,后来就找到了通过XML文件存储程序参数的方法。本文中使用dom4j读取xml文件XMLReader类import java.io.File;import java.util.Iterator;import org.dom4j.Document;import org.dom4j.Eleme...

weixin_29879257的博客 1055

java读取配置文件( properties 与 xml )

一、读取properties文件:public class Properties{ public static void main(String[] args){ Properties pt = new Properties();//创建一个Properties对象 try { String url = pt.getProperties();//调用Properties对

qq_40375627的博客 717

java xml作为配置文件,读取

  每个项目都需要配置文件来把可变的东西抽出来,方便程序的开发和维护:  自己编写了一个xml文件读取类,并可以以字符串形式调用xml文件中的属性与其值,其实也可以,直接一个static函数直接获得属性与其值,然而,我没这么做。估计这么做会更好。不多说,就算是改也容易。先把source提供出来:/* * Property.java * * Created on 2008.7.11,

Jimmybly Lee 的专栏 2165

java property xml_Java Properties配置文件和XML配置文件读取

一、properties类读取配置文件1、从项目中读取properties配置文件,新建一个main程序,对应位置建立一个名称为config.properties配置文件,随意放置一些键值对。IDEA建立配置文件,对应package鼠标右键,点击New,再点击Resource Bundle,弹出对话框输入名称保存即可。2、以下实例,读取配置文件,然后遍历key值和value值,采用此种方式读取项目...

weixin_33134401的博客 493

java xml properties_java读取xml/.properties配置文件

package org.ifocus.crawler.main;import java.io.BufferedInputStream;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.util.Enumeration;import java.util.It...

weixin_39636608的博客 185
上一篇: springboot项目启动报错:找不到或无法加载主类
下一篇: Java中byte数组和文件的互转方式
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值