Class XmlUtil

java.lang.Object
com.sure.tool.xml.XmlUtil

public class XmlUtil extends Object
XML 工具类(最小实现):Map/Bean 与 XML 互转、转义,基于 JDK DOM,参考 Hutool 的 XmlUtil 设计。

仅支持元素层级与文本内容(忽略属性);同名兄弟元素解析为 List。

English: XML parsing and serialization helpers built on the JDK XML APIs.

Since:
0.1.0
Author:
suretool
  • Method Details

    • toXml

      public static String toXml(Map<String,Object> map, String rootName)
      Map 转 XML 字符串。
      Parameters:
      map - Map(值支持基本类型、Map、List/Collection)
      rootName - 根元素名
      Returns:
      XML 字符串
    • toXml

      public static String toXml(Object bean, String rootName)
      Bean 转 XML 字符串。
      Parameters:
      bean - Bean 对象
      rootName - 根元素名
      Returns:
      XML 字符串
    • parseXml

      public static Map<String,Object> parseXml(String xml)
      解析 XML 为 Map(根元素名作为键)。
      Parameters:
      xml - XML 字符串
      Returns:
      Map
    • parseXmlToBean

      public static <T> T parseXmlToBean(String xml, Class<T> beanClass)
      解析 XML 为 Bean。
      Type Parameters:
      T - Bean 类型
      Parameters:
      xml - XML 字符串
      beanClass - Bean 类
      Returns:
      Bean 实例
    • escape

      public static String escape(String text)
      XML 转义(5 个预定义实体)。
      Parameters:
      text - 原文
      Returns:
      转义结果
    • unescape

      public static String unescape(String text)
      XML 反转义。
      Parameters:
      text - 转义文本
      Returns:
      原文
    • readXml

      public static Map<String,Object> readXml(String filePath)
      读取 XML 文件并解析为 Map。
      Parameters:
      filePath - XML 文件路径
      Returns:
      解析结果 Map
    • format

      public static String format(String xml, int indent)
      格式化 XML(缩进美化)。
      Parameters:
      xml - XML 字符串
      indent - 缩进空格数
      Returns:
      格式化后 XML
    • getByXPath

      public static String getByXPath(String xml, String xpath)
      使用 XPath 表达式从 XML 中取值。
      Parameters:
      xml - XML 字符串
      xpath - XPath 表达式
      Returns:
      匹配节点的文本值,无匹配返回 null