Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to configure Java persistence XML files

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Today, I would like to share with you the relevant knowledge points about how to configure Java persistent XML files. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article.

Select a format

Writing a configuration file is a rather complicated task. I have tried to save configuration items in a text file separated by commas, and I have also tried to save configuration items in very detailed YAML and XML. The most important thing for configuration files is consistency and regularity, which allows you to write code quickly and parse data from the configuration file, and to easily save and update the configuration when the user decides to make changes.

There are several popular configuration file formats. For most common configuration file formats, Java has a corresponding library, library. In this article, I will use the XML format. For some projects, you may choose to use XML because one of its outstanding features is its ability to provide a large amount of relevant metadata for the data it contains, while in other projects, you may not choose it because of the verbosity of XML. It is easy to use XML in Java because it contains many robust XML libraries by default.

XML Foundation

Discussing XML is a big topic. I have a book about XML, which has more than 700 pages. Fortunately, using XML does not require a lot of knowledge of its features. Like HTML, XML is a hierarchical markup language with opening and closing tags, and each tag (tag) can contain zero or more data. Here is a simple example snippet of XML:

Penguin

In this self-describing self-descriptive example, the XML parser uses the following concepts:

Document Document: the tag marks the beginning of a document, and the tag marks the end of the document.

Node Node: the label represents a node.

In the element Element:Penguin, an element is represented from the beginning.

Content Content: in the element, the string Penguin is the content.

Believe it or not, as long as you understand the above concepts, you can start writing and parsing XML files.

Create a sample configuration file

To learn how to parse XML files, all you need is a minimalist sample file. Suppose you now have a configuration file that holds properties about a graphical interface window:

Dark 0 Tango

Create a directory called ~ / .config/DemoXMLParser:

$mkdir ~ / .config/DemoXMLParser

In Linux, the ~ /. Config directory is the default location for configuration files, which is defined in the specification of the Free Desktop working Group. If you are using an operating system that does not follow the Freedesktop standard of the Free Desktop working Group, you can still use this directory, but you need to create these directories yourself.

Copy the sample configuration file for XML, paste it, and save it as ~ / .config/DemoXMLParser/myconfig.xml file.

Parsing XML using Java

If you are a beginner in Java, you can read my 7 tips for Java starter developers first. Once you are familiar with Java, open your favorite integrated development tool (IDE) and create a new project. I will name my new project myConfigParser.

Instead of focusing too much on dependency imports and exception catching at first, you can try instantiating a parser with the standard Java extensions in the javax and java.io packages. If you use IDE, it will prompt you to import the appropriate dependencies. If not, you can also find the complete code later in the article, where there is a complete list of dependencies.

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 ()

This sample code uses the java.nio.Paths class to find the user's home directory and then splice the path to the default configuration file. Next, it uses the java.io.File class to define the configuration file as a File object.

It then uses the javax.xml.parsers.DocumentBuilder and javax.xml.parsers.DocumentBuilderFactory classes to create an internal document constructor so that Java programs can import and parse XML data.

Finally, Java creates a document object called doc and loads the configFile file into this object. It reads and normalizes XML data by using the org.w3c.dom package.

That's basically it. In theory, you have finished the data parsing. 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.

Use Java to access the value of XML

To get data from the XML document you have read is to first find a specific node and then iterate through all the elements it contains. Usually we use multiple loop statements to traverse the elements in the node, but to keep the code readable, I use as few loop statements as possible:

NodeList nodes = doc.getElementsByTagName ("window"); for (int I = 0; I < nodes.getLength (); iTunes +) {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 ();}}

This sample code uses the org.w3c.dom.NodeList class to create a NodeList object named nodes. This object contains all the child nodes of the name matching string window. In fact, there is only one such node, because only one is configured in the sample configuration file in this article.

Next, it uses a for loop to traverse the nodes list. The specific process is: take out one by one according to the order in which the nodes appear, and then give it to an if-then clause to deal with. This if-then clause creates an Element object named myelement that contains all the elements under the current node. You can query these elements using methods such as getChildNodes and getElementById, and other query methods are recorded in the project.

In this example, each element is the configured key. The configured value is stored in the content of the element, and you can use the .getTextContent method to extract the configured value.

Run the code in your IDE (or run the compiled binaries):

$java. / DemoXMLParser.javaProperty = windowTheme = DarkFullscreen = 0Icon set = Tango

Here is a complete code example:

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 () ) {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 updates XML with Java

Users change a preference from time to time, and the org.w3c.dom library can help you update the contents of a XML element. You just need to select the XML element, just as you do when you read it. At this point, however, instead of using the .getTextContent method, you use the .setTextContent method.

UpdatePref = myelement.getElementsByTagName ("fullscreen") .item (0); updatePref.setTextContent ("1"); System.out.println ("Updated fullscreen to" + myelement.getElementsByTagName ("fullscreen") .item (0) .getTextContent ())

Doing so will change the XML document in the application's memory, but the data has not yet been written back to disk. With javax and W3C libraries, you can write the XML you read back to the configuration file.

TransformerFactory transformerFactory = TransformerFactory.newInstance (); Transformer xtransform;xtransform = transformerFactory.newTransformer (); DOMSource mydom = new DOMSource (doc); StreamResult streamResult = new StreamResult (configFile); xtransform.transform (mydom, streamResult)

Doing so will write the converted data without warning and overwrite the previous configuration.

Here is the complete code, including the operation to update the XML:

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 (); iTunes +) {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} / / how to ensure that there is no problem with the configuration

Writing a configuration file seems like a fairly simple task. At first, you may use a simple text format because your application has only a few configuration items. However, as you introduce more configuration items, reading or writing the wrong data may bring unexpected errors to your application. One way to help you keep the configuration process safe and error-free is to use a canonical format like XML and then rely on the built-in capabilities of the programming language you use to handle these complex things.

That's why I like using Java and XML. Java reminds me whenever I try to read the wrong configuration value. Usually, this is because the node I'm trying to get in the code doesn't exist in the XML path I expect. The highly structured format of XML helps keep the code reliable, which is good for both users and developers.

These are all the contents of the article "how to configure Java persistence XML files". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report