杰瑞科技汇

Java如何高效去除XML标签?

“去掉 XML”指的是以下几种操作之一:

  1. 去掉 XML 标签(标签/元素名),只保留文本内容:将 <name>张三</name> 变成 张三
  2. 去掉 XML 声明(<?xml ... ?>:从文件开头移除第一行。
  3. 去掉整个 XML 文档,只处理其中的数据:将 XML 数据解析到 Java 对象或 Map 中,然后直接操作这些对象,不再关心 XML 格式。
  4. 移除 XML 文件:从文件系统中删除整个 .xml 文件。

下面我将针对这四种情况,分别提供 Java 代码示例。


去掉 XML 标签,只保留文本内容

这是最常见的需求,通常意味着你需要“提取”XML 中的数据,有几种方法可以实现。

方法 1:使用 DOM 解析器(标准 Java API)

DOM 解析器会将整个 XML 文档读入内存,形成一个树形结构,你可以遍历这个树来获取文本内容。

示例代码:

import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.ByteArrayInputStream;
import java.io.IOException;
public class RemoveXmlTagsWithDom {
    public static String extractTextFromXml(String xmlString) {
        try {
            // 1. 创建 DocumentBuilderFactory 和 DocumentBuilder
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            // 2. 解析 XML 字符串
            Document document = builder.parse(new ByteArrayInputStream(xmlString.getBytes()));
            // 3. 获取根元素
            Element root = document.getDocumentElement();
            // 4. 递归提取所有文本节点
            StringBuilder textBuilder = new StringBuilder();
            extractTextRecursive(root, textBuilder);
            return textBuilder.toString().trim();
        } catch (Exception e) {
            e.printStackTrace();
            return "Error parsing XML: " + e.getMessage();
        }
    }
    private static void extractTextRecursive(Node node, StringBuilder textBuilder) {
        // 如果是文本节点,且不是空白字符,则追加内容
        if (node.getNodeType() == Node.TEXT_NODE) {
            String text = node.getTextContent().trim();
            if (!text.isEmpty()) {
                textBuilder.append(text).append(" ");
            }
        }
        // 递归处理所有子节点
        NodeList children = node.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            extractTextRecursive(children.item(i), textBuilder);
        }
    }
    public static void main(String[] args) {
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                     "<book>\n" +
                     "    <title>Java Programming</title>\n" +
                     "    <author>John Doe</author>\n" +
                     "    <chapter id=\"1\">\n" +
                     "        <title>Introduction</title>\n" +
                     "        <para>This is the first paragraph.</para>\n" +
                     "    </chapter>\n" +
                     "</book>";
        String plainText = extractTextFromXml(xml);
        System.out.println("提取的纯文本内容:");
        System.out.println(plainText);
        // 输出:
        // 提取的纯文本内容:
        // Java Programming John Doe Introduction This is the first paragraph.
    }
}

方法 2:使用 XPath(更直接,适合提取特定路径的文本)

如果你只想获取特定元素的文本,XPath 是最简单高效的方法。

示例代码:

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import java.io.ByteArrayInputStream;
public class ExtractTextWithXpath {
    public static void main(String[] args) throws Exception {
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                     "<book>\n" +
                     "    <title>Effective Java</title>\n" +
                     "    <author>Joshua Bloch</author>\n" +
                     "</book>";
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        Document document = factory.newDocumentBuilder()
                                  .parse(new ByteArrayInputStream(xml.getBytes()));
        XPath xpath = XPathFactory.newInstance().newXPath();
        // 1. 提取单个元素的文本
        String title = (String) xpath.evaluate("/book/title", document, XPathConstants.STRING);
        System.out.println("书名: " + title); // 输出: 书名: Effective Java
        // 2. 提取多个元素的文本
        NodeList authors = (NodeList) xpath.evaluate("//author", document, XPathConstants.NODESET);
        System.out.print("作者列表: ");
        for (int i = 0; i < authors.getLength(); i++) {
            System.out.print(authors.item(i).getTextContent() + " ");
        } // 输出: 作者列表: Joshua Bloch 
    }
}

去掉 XML 声明 (<?xml ... ?>)

这个比较简单,因为 XML 声明总是在文件的最开头,你可以通过字符串操作来移除它。

示例代码:

public class RemoveXmlDeclaration {
    public static String removeDeclaration(String xmlContent) {
        // XML 声明以 "<?xml" 开头,以 "?>" 可能包含换行符
        // 使用正则表达式匹配并替换为空字符串
        return xmlContent.replaceAll("<\\?xml.*?\\?>", "").trim();
    }
    public static void main(String[] args) {
        String xmlWithDeclaration = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<root>Content</root>";
        String xmlWithoutDeclaration = removeDeclaration(xmlWithDeclaration);
        System.out.println("移除声明前:");
        System.out.println(xmlWithDeclaration);
        System.out.println("\n移除声明后:");
        System.out.println(xmlWithoutDeclaration);
    }
}

去掉 XML 格式,处理数据(最佳实践)

这通常意味着你需要将 XML 数据反序列化(Unmarshal)到 Java 对象中,这样你就可以在纯 Java 环境中操作数据,而完全“忘记”它的 XML 来源。

步骤:

  1. 定义 Java 类(POJO):这些类的结构需要与 XML 结构对应。
  2. 使用 JAXB:这是 Java 标准库中用于 XML 绑定的工具(Java Architecture for XML Binding)。

示例代码:

定义 Java 类 (Book.java, Author.java)

// Author.java
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement // 标记为XML根元素
public class Author {
    private String name;
    @XmlElement // 映射到XML元素
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}
// Book.java
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Book {
    private String title;
    private Author author;
    @XmlElement
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    @XmlElement
    public Author getAuthor() {
        return author;
    }
    public void setAuthor(Author author) {
        this.author = author;
    }
}

使用 JAXB 进行转换

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
public class JaxbExample {
    public static void main(String[] args) throws Exception {
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                     "<book>\n" +
                     "    <title>Clean Code</title>\n" +
                     "    <author>\n" +
                     "        <name>Robert C. Martin</name>\n" +
                     "    </author>\n" +
                     "</book>";
        // 1. 创建 JAXBContext,指定要转换的类
        JAXBContext jaxbContext = JAXBContext.newInstance(Book.class);
        // 2. 创建 Unmarshaller
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        // 3. 从 XML 字符串转换为 Java 对象
        Book book = (Book) unmarshaller.unmarshal(new StringReader(xml));
        // 4. 你可以直接操作 Java 对象,完全不用关心 XML
        System.out.println("书名: " + book.getTitle());
        System.out.println("作者: " + book.getAuthor().getName());
        // 你可以轻松地修改数据
        book.getAuthor().setName("Uncle Bob");
        System.out.println("修改后的作者: " + book.getAuthor().getName());
    }
}

移除 XML 文件

这个最简单,直接使用 Java 的文件操作 API 即可。

示例代码:

import java.io.File;
import java.io.IOException;
public class RemoveXmlFile {
    public static void deleteXmlFile(String filePath) {
        File file = new File(filePath);
        // 检查文件是否存在
        if (file.exists()) {
            // 尝试删除文件
            if (file.delete()) {
                System.out.println("文件 " + filePath + " 已成功删除。");
            } else {
                System.out.println("删除文件 " + filePath + " 失败。");
            }
        } else {
            System.out.println("文件 " + filePath + " 不存在。");
        }
    }
    public static void main(String[] args) {
        // 假设有一个名为 data.xml 的文件在当前目录
        String xmlFilePath = "data.xml";
        deleteXmlFile(xmlFilePath);
    }
}
你的目标 推荐方法 优点 缺点
去掉标签,只留文本 XPath (简单提取) 或 DOM 递归 (提取所有) 灵活,强大 需要处理 XML 解析异常
去掉 XML 声明 字符串替换 (replaceAll) 极其简单,性能高 不够健壮,如果格式复杂可能出错
处理数据,忽略 XML JAXB (推荐) 最佳实践,代码最清晰,面向对象 需要定义对应的 Java 类
删除整个 XML 文件 java.io.File.delete() 最直接,功能明确

请根据您的具体需求选择最合适的方案,对于大多数数据处理场景,使用 JAXB 将 XML 转换为 Java 对象是最佳选择

分享:
扫描分享到社交APP
上一篇
下一篇