Java XML解析

  • Post author:
  • Post category:java




Java引用XStream解析xml文件生成一个对应的对象

xml文本

<?xml version="1.0" encoding="UTF-8"?>
<基本信息>
    <姓名>张三</姓名>
    <code>450011</code>
</基本信息>

映射对象

@XStreamAlias("基本信息")
public class MarriageRegistBasicInfoXmlModel implements Serializable {

    @XStreamAlias("姓名")
    private String name;
    
    @XStreamAlias("code")
    private String code;
}

xml文本和映射类主要是用@XStreamAlias(“基本信息”)进行绑定关系,支持中英文

核心代码

try (
                FileInputStream in = new FileInputStream("c://basicInfo.xml")
                ){
            XStream xStream = new XStream();
            // XStream设置默认安全防护 导致com.thoughtworks.xstream.security.ForbiddenClassException
            //XStream.setupDefaultSecurity(xStream);
            //	尽量限制所需的最低权限 这条语句解决com.thoughtworks.xstream.security.ForbiddenClassException
            xStream.addPermission(AnyTypePermission.ANY);
            xStream.autodetectAnnotations(true);
            xStream.processAnnotations(MarriageRegistBasicInfoXmlModel.class);
            byte[] bytes = new byte[1024];
            //每一次读取数据长度
            int currentRead;
            //已读取长度
            int alreadyRead = 0;
            //读取的所有数据
            byte[] all = null;
            while ((currentRead = in.read(bytes)) != -1) {
                int tempLength = alreadyRead + currentRead;
                byte[] temp = new byte[tempLength];
                if (Objects.nonNull(all)) {
                    //将之前已读数据复制到临时容器
                    System.arraycopy(all, 0, temp, 0, alreadyRead);
                }
                //当前读到的数据拼接到之前的已读数据
                System.arraycopy(bytes, 0, temp, alreadyRead, currentRead);
                //更新已读长度
                alreadyRead = tempLength;
                //最新的已读数据
                all = temp;
            }
            //读取xml文件必须全部读取完后然后转为字符串
            if (Objects.nonNull(all)) {
                MarriageRegistBasicInfoXmlModel basicInfoXmlModel = (MarriageRegistBasicInfoXmlModel) xStream.fromXML(new String(all));
                //todo:basicInfoXmlModel此对象就是解析得到的xml数据,根据自身业务进行具体操作
            }
        }catch (Exception e) {
            e.printStackTrace();
        }

jar包

<dependency>
       <groupId>com.thoughtworks.xstream</groupId>
       <artifactId>xstream</artifactId>
       <version>1.4.10</version>
</dependency>

整体梳理就是xml和映射对象根据@XStreamAlias(“基本信息”)注解绑定,XStream设置后进行对应解析得到对应的对象,然后根据具体业务进行下一步操作



版权声明:本文为SmilingBoy000原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。