使用 XML 工具: jdom
小于 1 分钟
JDOM 是一种解析 XML 的 Java 工具包。 JDOM 是 Breet Mclaughlin 和 Jason Hunter 两大 Java 高手的创作成果,2000 年初,JDOM 作为一个开放源代码项目正式开始研发。
https://github.com/LawssssCat/blog/tree/master/code/demo-java-xml/n03-jdom-usage/test/java/org/example/读
XML 文件
<?xml version="1.0" encoding="utf-8" ?>
<my-content>
<web-site>http://www.example.org</web-site>
<owner>steven</owner>
<description>原生 java xml 操作测试消息</description>
<posts>
<!-- 我是注释 -->
<post id="P001">
<title>文章标题01</title>
<content>hello world 01!</content>
</post>
<post id="P002">
<title>文章标题02</title>
<content>hello world 02!</content>
</post>
</posts>
</my-content>
测试用例
package example;
import lombok.extern.slf4j.Slf4j;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.filter.AbstractFilter;
import org.jdom2.input.SAXBuilder;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@Slf4j
public class XmlJDomReadTest {
Document read;
@BeforeEach
void beforeEach() {
SAXBuilder saxBuilder = new SAXBuilder();
try {
read = saxBuilder.build(getClass().getResource("/message001.xml"));
} catch (JDOMException | IOException e) {
throw new RuntimeException(e);
}
}
@Test
void test_getRootElement() {
Element rootElement = read.getRootElement();
Assertions.assertEquals("my-content", rootElement.getQualifiedName());
Assertions.assertEquals(2, rootElement.getChild("posts").getChildren().size());
Assertions.assertArrayEquals(new String[] {"P001", "P002"}, rootElement.getChild("posts").getChildren().stream().map(e -> e.getAttribute("id").getValue()).toArray());
}
static class ParentFilter extends AbstractFilter<Element> {
private final Element p;
ParentFilter(Element p) {
this.p = p;
}
@Override
public Element filter(Object content) {
if(content instanceof Element) {
Element e = (Element) content;
if (p.equals(e.getParentElement())) {
return e;
}
}
return null;
}
}
@Test
void test_nodeIterator() {
int countContentElement = 0;
int countPostElement = 0;
List<String> contentElementQNameList = new ArrayList<>();
List<String> postElementIdList = new ArrayList<>();
// test
Element rootElement = read.getRootElement();
Iterator<Element> contentIterator = rootElement.getDescendants(new ParentFilter(rootElement));
while (contentIterator.hasNext()) {
countContentElement++;
Element contentElement = contentIterator.next();
System.out.println("contentElement = " + contentElement);
contentElementQNameList.add(contentElement.getQualifiedName());
if("posts".equals(contentElement.getQualifiedName())) {
Iterator<Element> postIterator = contentElement.getDescendants(new ParentFilter(contentElement));
while (postIterator.hasNext()) {
countPostElement++;
Element post = postIterator.next();
System.out.println("postElement = " + post);
postElementIdList.add(post.getAttributeValue("id"));
}
}
}
Assertions.assertEquals(4, countContentElement);
Assertions.assertEquals(2, countPostElement);
Assertions.assertArrayEquals(new String[] {"web-site", "owner", "description", "posts"}, contentElementQNameList.toArray());
Assertions.assertArrayEquals(new String[] {"P001", "P002"}, postElementIdList.toArray());
}
}
写
测试用例
package example;
import org.jdom2.Attribute;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import utils.IOUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
public class XmlJDomWriteTest {
private Element addContent(Element p, Element c) {
p.addContent(c);
return c;
}
@Test
void test() throws IOException {
Element content = new Element("content");
Element owner = addContent(content, new Element("owner"));
owner.setText("steven");
Element posts = addContent(content, new Element("posts"));
for (int i = 0; i < 2; i++) {
Element post = addContent(posts, new Element("post"));
List<Attribute> attributes = Collections.singletonList(new Attribute("id", "P00" + i));
post.setAttributes(attributes);
}
// write
File file = new File(Objects.requireNonNull(getClass().getResource("/")).getFile(), getClass().getName() + ".xml");
try (FileOutputStream fileOutputStream = new FileOutputStream(file)) {
XMLOutputter xmlWriter = new XMLOutputter();
Format format = Format.getCompactFormat();
format.setEncoding(StandardCharsets.UTF_8.name());
xmlWriter.setFormat(format);
xmlWriter.output(content, fileOutputStream);
}
// validate
Assertions.assertTrue(file.exists());
Assertions.assertEquals("<content><owner>steven</owner><posts><post id=\"P000\" /><post id=\"P001\" /></posts></content>",
IOUtils.readFile(file));
}
}
参考:
- https://www.cnblogs.com/wordless/p/16208704.html