Table of Contents
Choose a format
XML Basics
Create a sample configuration file
Use Java to parse XML
使用 Java 访问 XML 的值
使用 Java 更新 XML
如何保证配置不出问题
Home Java javaTutorial How to configure Java persistence XML file

How to configure Java persistence XML file

May 04, 2023 am 09:40 AM
java xml

<h4 id="Choose-a-format">Choose a format</h4> <p>Writing a configuration file is a rather complicated matter. I've tried saving configuration items in a comma-separated text file, and I've tried saving configuration items in very verbose YAML and XML. For configuration files, the most important thing is to have consistency and regularity. They allow you to write code easily and quickly and parse data from the configuration file; at the same time, when the user decides to make changes, it is easy to save them. and update configuration. </p> <p>There are currently several popular configuration file formats. For most common configuration file formats, Java has corresponding libraries. In this article, I will use XML format. For some projects, you might choose to use XML because one of its standout features is its ability to provide a wealth of relevant metadata for the data it contains, while for other projects, you might not choose XML because of its verbosity. Working with XML in Java is very easy as it includes many robust XML libraries by default. </p> <h4 id="XML-Basics">XML Basics</h4> <p>Discussing XML is a big topic. I have a book on XML that is over 700 pages long. Fortunately, working with XML doesn't require an intimate knowledge of its many features. Just like HTML, XML is a layered markup language with opening and closing tags, each of which can contain zero or more data. Here is a simple example snippet of XML: </p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'><xml> <node> <element>Penguin</element> </node> </xml></pre><div class="contentsignin">Copy after login</div></div><p>In this self-descriptive example, the XML parser uses the following concepts: </p><ul class=" list-paddingleft-2"><li><p>Documentation Document: The <code><xml></code> tag marks the beginning of a document, and the <code></xml></code> tag marks the end of this document. </p></li><li><p>Node Node: <code><node></code> The label represents a node. </p></li><li><p>Element: <code><element>Penguin</element></code>, from the beginning <code><</code> to the last <code>&gt ;</code> represents an element. </p></li><li><p> Content: In the <code><element></code> element, the string <code>Penguin</code> is the content. </p></li></ul><p>Believe it or not, as long as you understand the above concepts, you can start writing and parsing XML files. </p><h4 id="Create-a-sample-configuration-file">Create a sample configuration file</h4><p>To learn how to parse XML files, all you need is a minimalist sample file. Suppose there is a configuration file, which saves the properties of a graphical interface window: </p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'><xml> <window> <theme>Dark</theme> <fullscreen>0</fullscreen> <icons>Tango</icons> </window> </xml></pre><div class="contentsignin">Copy after login</div></div><p>Create a directory named <code>~/.config/DemoXMLParser</code>: </p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>$ mkdir ~/.config/DemoXMLParser</pre><div class="contentsignin">Copy after login</div></div><p>In Linux, the <code>~/.config</code> directory is the default location for storing configuration files, which is defined in the specifications of the Free Desktop Working Group. If you are using an operating system that does not adhere to the Freedesktop standards, you can still use this directory, but you will need to create these directories yourself. </p><p>Copy the XML sample configuration file, paste and save it as <code>~/.config/DemoXMLParser/myconfig.xml</code> file. </p><h4 id="Use-Java-to-parse-XML">Use Java to parse XML</h4><p>If you are a beginner in Java, you can first read the 7 tips I wrote for beginner Java developers. Once you are more familiar with Java, open your favorite integrated development tool (IDE) and create a new project. I will name my new project <code>myConfigParser</code>. </p><p>Don’t pay too much attention to dependency imports and exception catching at the beginning. You can first try to instantiate using the standard Java extensions in the <code>javax</code> and <code>java.io</code> packages. A parser. If you are using an IDE, it will prompt you to import the appropriate dependencies. If not, you can find the complete code later in the article, which has a complete list of dependencies. </p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>Path configPath = Paths.get(System.getProperty("user.home"), ".config", "DemoXMLParser"); File configFile = new File(configPath.toString(), "myconfig.xml"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = null; builder = factory.newDocumentBuilder(); Document doc = null; doc = builder.parse(configFile); doc.getDocumentElement().normalize();</pre><div class="contentsignin">Copy after login</div></div><p>This sample code uses the <code>java.nio.Paths</code> class to find the user's home directory, and then splices the path to the default configuration file. Then, it uses the <code>java.io.File</code> class to define the configuration file as a <code>File</code> object. </p><p>Next, it uses the two classes <code>javax.xml.parsers.DocumentBuilder</code> and <code>javax.xml.parsers.DocumentBuilderFactory</code> to create an internal document structure Converter so that Java programs can import and parse XML data. </p><p>Finally, Java creates a document object called <code>doc</code> and loads the <code>configFile</code> file into this object. Using the <code>org.w3c.dom</code> package, it reads and normalizes XML data. </p><p>That’s basically it. In theory, you have completed the data analysis work. However, data parsing is of little use if you don't have access to the data. So, let's write some more queries to read important property values ​​from your configuration. </p><h4 id="使用-Java-访问-XML-的值">使用 Java 访问 XML 的值</h4><p>从你已经读取的 XML 文档中获取数据,其实就是要先找到一个特定的节点,然后遍历它包含的所有元素。通常我们会使用多个循环语句来遍历节点中的元素,但是为了保持代码可读性,我会尽可能少地使用循环语句:</p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>NodeList nodes = doc.getElementsByTagName("window"); for (int i = 0; i < nodes.getLength(); i++) { Node mynode = nodes.item(i); System.out.println("Property = " + mynode.getNodeName()); if (mynode.getNodeType() == Node.ELEMENT_NODE) { Element myelement = (Element) mynode; System.out.println("Theme = " + myelement.getElementsByTagName("theme").item(0).getTextContent()); System.out.println("Fullscreen = " + myelement.getElementsByTagName("fullscreen").item(0).getTextContent()); System.out.println("Icon set = " + myelement.getElementsByTagName("icons").item(0).getTextContent()); } }</pre><div class="contentsignin">Copy after login</div></div><p>这段示例代码使用了 <code>org.w3c.dom.NodeList</code> 类,创建了一个名为 <code>nodes</code> 的 <code>NodeList</code> 对象。这个对象包含了所有名字匹配字符串 <code>window</code> 的子节点,实际上这样的节点只有一个,因为本文的示例配置文件中只配置了一个。</p><p>紧接着,它使用了一个 <code>for</code> 循环来遍历 <code>nodes</code> 列表。具体过程是:根据节点出现的顺序逐个取出,然后交给一个 <code>if-then</code> 子句处理。这个 <code>if-then</code> 子句创建了一个名为 <code>myelement</code> 的 <code>Element</code> 对象,其中包含了当前节点下的所有元素。你可以使用例如 <code>getChildNodes</code> 和 <code>getElementById</code> 方法来查询这些元素,项目中还 记录了 其他查询方法。</p><p>在这个示例中,每个元素就是配置的键。而配置的值储存在元素的内容中,你可以使用 <code>.getTextContent</code> 方法来提取出配置的值。</p><p>在你的 IDE 中运行代码(或者运行编译后的二进制文件):</p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>$ java ./DemoXMLParser.java Property = window Theme = Dark Fullscreen = 0 Icon set = Tango</pre><div class="contentsignin">Copy after login</div></div><p>下面是完整的代码示例:</p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>package myConfigParser; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class ConfigParser { public static void main(String[] args) { Path configPath = Paths.get(System.getProperty("user.home"), ".config", "DemoXMLParser"); File configFile = new File(configPath.toString(), "myconfig.xml"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = null; try { builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); } Document doc = null; try { doc = builder.parse(configFile); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } doc.getDocumentElement().normalize(); NodeList nodes = doc.getElementsByTagName("window"); for (int i = 0; i < nodes.getLength(); i++) { Node mynode = nodes.item(i); System.out.println("Property = " + mynode.getNodeName()); if (mynode.getNodeType() == Node.ELEMENT_NODE) { Element myelement = (Element) mynode; System.out.println("Theme = " + myelement.getElementsByTagName("theme").item(0).getTextContent()); System.out.println("Fullscreen = " + myelement.getElementsByTagName("fullscreen").item(0).getTextContent()); System.out.println("Icon set = " + myelement.getElementsByTagName("icons").item(0).getTextContent()); } // close if } // close for } // close method } //close class</pre><div class="contentsignin">Copy after login</div></div><h4 id="使用-Java-更新-XML">使用 Java 更新 XML</h4><p>用户时不时地会改变某个偏好项,这时候 <code>org.w3c.dom</code> 库就可以帮助你更新某个 XML 元素的内容。你只需要选择这个 XML 元素,就像你读取它时那样。不过,此时你不再使用 <code>.getTextContent</code> 方法,而是使用 <code>.setTextContent</code> 方法。</p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>updatePref = myelement.getElementsByTagName("fullscreen").item(0); updatePref.setTextContent("1"); System.out.println("Updated fullscreen to " + myelement.getElementsByTagName("fullscreen").item(0).getTextContent());</pre><div class="contentsignin">Copy after login</div></div><p>这么做会改变应用程序内存中的 XML 文档,但是还没有把数据写回到磁盘上。配合使用 <code>javax</code> 和 <code>w3c</code> 库,你就可以把读取到的 XML 内容写回到配置文件中。</p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer xtransform; xtransform = transformerFactory.newTransformer(); DOMSource mydom = new DOMSource(doc); StreamResult streamResult = new StreamResult(configFile); xtransform.transform(mydom, streamResult);</pre><div class="contentsignin">Copy after login</div></div><p>这么做会没有警告地写入转换后的数据,并覆盖掉之前的配置。</p><p>下面是完整的代码,包括更新 XML 的操作:</p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>package myConfigParser; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class ConfigParser { public static void main(String[] args) { Path configPath = Paths.get(System.getProperty("user.home"), ".config", "DemoXMLParser"); File configFile = new File(configPath.toString(), "myconfig.xml"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = null; try { builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } Document doc = null; try { doc = builder.parse(configFile); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } doc.getDocumentElement().normalize(); Node updatePref = null; // NodeList nodes = doc.getChildNodes(); NodeList nodes = doc.getElementsByTagName("window"); for (int i = 0; i < nodes.getLength(); i++) { Node mynode = nodes.item(i); System.out.println("Property = " + mynode.getNodeName()); if (mynode.getNodeType() == Node.ELEMENT_NODE) { Element myelement = (Element) mynode; System.out.println("Theme = " + myelement.getElementsByTagName("theme").item(0).getTextContent()); System.out.println("Fullscreen = " + myelement.getElementsByTagName("fullscreen").item(0).getTextContent()); System.out.println("Icon set = " + myelement.getElementsByTagName("icons").item(0).getTextContent()); updatePref = myelement.getElementsByTagName("fullscreen").item(0); updatePref.setTextContent("2"); System.out.println("Updated fullscreen to " + myelement.getElementsByTagName("fullscreen").item(0).getTextContent()); } // close if }// close for // write DOM back to the file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer xtransform; DOMSource mydom = new DOMSource(doc); StreamResult streamResult = new StreamResult(configFile); try { xtransform = transformerFactory.newTransformer(); xtransform.transform(mydom, streamResult); } catch (TransformerException e) { e.printStackTrace(); } } // close method } //close class</pre><div class="contentsignin">Copy after login</div></div><h4 id="如何保证配置不出问题">如何保证配置不出问题</h4> <p>编写配置文件看上去是一个还挺简单的任务。一开始,你可能会用一个简单的文本格式,因为你的应用程序只要寥寥几个配置项而已。但是,随着你引入了更多的配置项,读取或者写入错误的数据可能会给你的应用程序带来意料之外的错误。一种帮助你保持配置过程安全、不出错的方法,就是使用类似 XML 的规范格式,然后依靠你用的编程语言的内置功能来处理这些复杂的事情。</p> <p>这也正是我喜欢使用 Java 和 XML 的原因。每当我试图读取错误的配置值时,Java 就会提醒我。通常,这是由于我在代码中试图获取的节点,并不存在于我期望的 XML 路径中。XML 这种高度结构化的格式帮助了代码保持可靠性,这对用户和开发者来说都是有好处的。</p>

The above is the detailed content of How to configure Java persistence XML file. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

Java Made Simple: A Beginner's Guide to Programming Power Java Made Simple: A Beginner's Guide to Programming Power Oct 11, 2024 pm 06:30 PM

Java Made Simple: A Beginner's Guide to Programming Power Introduction Java is a powerful programming language used in everything from mobile applications to enterprise-level systems. For beginners, Java's syntax is simple and easy to understand, making it an ideal choice for learning programming. Basic Syntax Java uses a class-based object-oriented programming paradigm. Classes are templates that organize related data and behavior together. Here is a simple Java class example: publicclassPerson{privateStringname;privateintage;

Java Program to insert an element at the Bottom of a Stack Java Program to insert an element at the Bottom of a Stack Feb 07, 2025 am 11:59 AM

A stack is a data structure that follows the LIFO (Last In, First Out) principle. In other words, The last element we add to a stack is the first one to be removed. When we add (or push) elements to a stack, they are placed on top; i.e. above all the

See all articles