您想学习如何从java读写XML文件吗?
XML文件用于各种目的,包括存储数据。在JSON流行之前,XML是表示、存储和传输结构化数据的首选格式。尽管近年来XML的流行程度有所下降,但您可能偶尔会遇到它,因此从代码中学习如何使用它是很重要的。
javastandardedition(SE)包括javaapi for XML Processing(JAXP),这是一个涵盖XML处理的大多数方面的总括术语。其中包括:
在本文中,我们使用domapi演示如何从java读取和写入XML文件。我们将在以后的文章中介绍另外两个api。
在本文中,我们使用以下示例XML演示这些概念,可以在这里找到:
<?xml version="1.0"?>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applicati***
with XML.</description>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
...
让我们看看使用domapi读取XML文件所需的基本步骤。
第一步是获取DocumentBuilder的实例。生成器用于解析XML文档。基本用法如下:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(false);
factory.setValidating(false);
DocumentBuilder builder = factory.newDocumentBuilder();
我们现在可以从XML根元素开始将整个文档加载到内存中。在我们的示例中,它是catalog元素。
File file = ...; // XML file to read
Document document = builder.parse(file);
Element catalog = document.getDocumentElement();
就这样,伙计们!读取XML的domapi非常简单。现在您可以从根元素catalog开始访问整个XML文档。现在让我们看看如何使用它。
既然我们有了XML根元素,就可以使用domapi来提取有趣的信息。
获取根元素的所有book子元素并在其上循环。注意getChildNodes()返回所有子元素,包括文本、注释等。出于我们的目的,我们只需要子元素,因此跳过其他元素。
NodeList books = catalog.getChildNodes();
for (int i = 0, ii = 0, n = books.getLength() ; i < n ; i++) {
Node child = books.item(i);
if ( child.getNodeType() != Node.ELEMENT_NODE )
continue;
Element book = (Element)child;
// work with the book Element here
}
给定父元素,如何找到特定的子元素?下面的静态方法返回第一个匹配的元素(如果找到),或者返回null。如您所见,该过程涉及到获取子节点列表,并在其中循环选择具有指定名称的元素节点。
static private Node findFirstNamedElement(Node parent,String tagName)
{
NodeList children = parent.getChildNodes();
for (int i = 0, in = children.getLength() ; i < in ; i++) {
Node child = children.item(i);
if ( child.getNodeType() != Node.ELEMENT_NODE )
continue;
if ( child.getNodeName().equals(tagName) )
return child;
}
return null;
}
注意,domapi将元素中的文本内容视为类型为text\u node的单独节点。此外,文本内容可能被分割成多个相邻的文本节点。因此,需要进行以下特殊处理来获取元素中的文本内容。
static private String getCharacterData(Node parent)
{
StringBuilder text = new StringBuilder();
if ( parent == null )
return text.toString();
NodeList children = parent.getChildNodes();
for (int k = 0, kn = children.getLength() ; k < kn ; k++) {
Node child = children.item(k);
if ( child.getNodeType() != Node.TEXT_NODE )
break;
text.append(child.getNodeValue());
}
return text.toString();
}
有了这些方便的函数,现在让我们看一些代码,从示例XML中列出一些信息。我们想展示每本书的详细信息,如图书目录中提供的信息。
NodeList books = catalog.getChildNodes();
for (int i = 0, ii = 0, n = books.getLength() ; i < n ; i++) {
Node child = books.item(i);
if ( child.getNodeType() != Node.ELEMENT_NODE )
continue;
Element book = (Element)child;
ii++;
String id = book.getAttribute("id");
String author = getCharacterData(findFirstNamedElement(child,"author"));
String title = getCharacterData(findFirstNamedElement(child,"title"));
String genre = getCharacterData(findFirstNamedElement(child,"genre"));
String price = getCharacterData(findFirstNamedElement(child,"price"));
String pubdate = getCharacterData(findFirstNamedElement(child,"pubdate"));
String descr = getCharacterData(findFirstNamedElement(child,"description"));
System.out.printf("%3d. book id = %s
" +
" author: %s
" +
" title: %s
" +
" genre: %s
" +
" price: %s
" +
" pubdate: %s
" +
" descr: %s
",
ii, id, author, title, genre, price, pubdate, descr);
}
Java提供了XML转换API来转换XML数据。我们使用这个API和身份转换来生成输出。
作为一个例子,让我们向上面的示例目录添加一个新的book元素。书的细节(如作者、标题等)可以从外部获得,也许可以从属性文件或数据库获得。我们使用以下属性文件来加载数据。
id=bk113
author=Jane Austen
title=Pride and Prejudice
genre=Romance
price=6.99
publish_date=2010-04-01
description="It is a truth universally acknowledged, that a single man in possession of a good fortune must be in want of a wife." So begins Pride and Prejudice, Jane Austen's witty comedy of manners-one of the most popular novels of all time-that features splendidly civilized sparring between the proud Mr. Darcy and the prejudiced Elizabeth Bennet as they play out their spirited courtship in a series of eighteenth-century drawing-room intrigues.
第一步是使用上述方法解析现有的XML文件。代码如下所示。
File file = ...; // XML file to read
Document document = builder.parse(file);
Element catalog = document.getDocumentElement();
我们使用java提供的properties类从properties文件加载数据。代码非常简单,如下所示。
String propsFile = ...;
Properties props = new Properties();
try (FileReader in = new FileReader(propsFile)) {
props.load(in);
}
加载属性后,我们将从属性文件中检索要添加的值。
String id = props.getProperty("id");
String author = props.getProperty("author");
String title = props.getProperty("title");
String genre = props.getProperty("genre");
String price = props.getProperty("price");
String publish_date = props.getProperty("publish_date");
String descr = props.getProperty("description");
现在让我们创建一个空的book元素。
Element book = document.createElement("book");
book.setAttribute("id", id);
将子元素添加到书中是很简单的。为了方便起见,我们在列表中收集所需的元素名称,并在循环中添加值。
List<String> elnames =Arrays.asList("author", "title", "genre", "price",
"publish_date", "description");
for (String elname : elnames) {
Element el = document.createElement(elname);
Text text = document.createTextNode(props.getProperty(elname));
el.appendChild(text);
book.appendChild(el);
}
catalog.appendChild(book);
就是这样做的。catalog元素现在添加了newbook元素。现在剩下的就是写出更新后的XML。
为了编写XML,我们需要一个Transformer实例,它的创建如下所示。注意,我们使用setOutputProperty()方法请求输出XML的缩进。
TransformerFactory tfact = TransformerFactory.newInstance();
Transformer tform = tfact.newTransformer();
tform.setOutputProperty(OutputKeys.INDENT, "yes");
tform.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3");
生成XML输出的最后一步是应用转换。结果显示在输出流上,系统输出.
tform.transform(new DOMSource(document), new StreamResult(System.out));
要将输出直接写入文件,请使用以下命令。
tform.transform(new DOMSource(document), new StreamResult(new File("output.xml")));
这就结束了本文关于使用domapi读写XML文件的内容。
您在应用程序中使用过domapi吗?表现如何?请在下面的评论中告诉我们。
...JavaScript对象表示法,有助于在各种平台之间交换数据。读写容易。JSON主要用于异步JavaScript(AJAX)和开发restfulweb服务。它也可以与许多语言一起使用,如java、C++、C++、Python。JSON的一些数据类型有Number、Boolean、String、Array、Objec...
Python是一种优秀的编程语言。语法可能看起来奇怪和不寻常,但它很容易学习和使用。它支持Minecraft Pi版,以及一系列网站和学术研究项目。 ...
...和其他编程语言)定义了网站的外观,但您永远不会看到代码的踪迹。你看到的是浏览器对它的解释。例如,字体格式或嵌入图像。 ...
Linux用户通常使用基于终端的工具(如nano和vim)编辑配置文件。如果您想以图形方式编辑一个文件,甚至是一个系统文件,gedit文本编辑器可以让您轻松自如。 文件,到处都是文件 关于Linux和其他基于Unix的操作系统(如macOS)...
...较可能是最容易的。HTML使用一组预定义的标记符号(短代码)来描述web页面上的内容格式。例如,下面的简单HTML代码使用标记将一些单词设置为粗体,一些设置为斜体: This is how you make <b>bold text</b> and this is how you make ...
从PHP镜像下载文件很烦人,因为在默认情况下,重定向器会将文件名的名称更改为“mirror”,那么如何解决这个问题呢?幸运的是,wget有一个简单的参数,您可以使用它来修复它—它对许多场景都很有用。 每当您想强制Wget命...
...险? 这些文件扩展名有潜在的危险,因为它们可能包含代码或执行任意命令。一个.exe文件有潜在的危险,因为它是一个可以做任何事情的程序(在Windows的用户帐户控制功能的限制范围内)。媒体文件-如.JPEG图像和.MP3音乐文件-...
在Windows中解决问题可能是一种痛苦,但是内置的可靠性监视器通过在一个简单的视图中显示计算机的可靠性和问题历史,为您提供了一个支撑。可靠性监视器是那些令人敬畏的Windows功能之一,很少有人知道或烦恼。但它非常有...