一、声明版本依赖

项目负责版本管理的pom依赖如下声明引用

  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.18</version>
        <relativePath/>
    </parent>

在定义share或者api的pom中

添加如下依赖,因为需要用到jackson xml的注解

 <dependency>
         <groupId>com.fasterxml.jackson.dataformat</groupId>
         <artifactId>jackson-dataformat-xml</artifactId>
  </dependency>

用的比较多是

@JacksonXmlRootElement 标注在类上
@JacksonXmlProperty 标注下属性上
@JacksonXmlElementWrapper 标注在集合属性上

具体怎么使用网上比我写的详细

应用pom添加如下依赖

 <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <exclusions>
                <exclusion>
                    <artifactId>jackson-core</artifactId>
                    <groupId>com.fasterxml.jackson.core</groupId>
                </exclusion>
            </exclusions>
        </dependency>

二、示例

小demo 

@Data
@JacksonXmlRootElement(localName = "ROOT")
public class XmlBean {

    @JacksonXmlProperty(localName = "Name")
    private String name;

    @JacksonXmlElementWrapper(localName = "List")
    private List<String> list;
}   



XmlMapper xmlMapper = new XmlMapper();
xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
System.out.println(xmlMapper.writeValueAsString(new XmlBean()));


输出
<?xml version='1.0' encoding='UTF-8'?><ROOT><Name/></ROOT>

对于有层级的集合

@Data
@JacksonXmlRootElement(localName = "ROOT")
public class XmlBean {

    @JacksonXmlProperty(localName = "Name")
    private String name;

    @JacksonXmlElementWrapper(localName = "List")
    @JacksonXmlProperty(localName = "Detail")
    private List<Detail> list;

    @Data
    public static class Detail{

        @JacksonXmlProperty(localName = "Key")
        private String key;
    }
}
  XmlBean xmlBean = new XmlBean();
        System.out.println(xmlMapper.writeValueAsString(xmlBean));
        xmlBean.setName("测试");
        XmlBean.Detail detail = new XmlBean.Detail();
        detail.setKey("key");
        xmlBean.setList(Lists.newArrayList(detail));
        System.out.println(xmlMapper.writerWithDefaultPrettyPrinter().writeValueAsString(xmlBean));

输出为

<ROOT>
  <Name>测试</Name>
  <List>
    <Detail>
      <Key>key</Key>
    </Detail>
  </List>
</ROOT>

同理,xml转bean

三、获取节点

 /**
     * 根据xml或者节点的值
     *
     * @param xml      指定xml如此
     * @param nodeName 节点名称,区分大小写
     * @return 节点对应的值
     * @throws JsonProcessingException 异常
     */
    public static String nodeValue(String xml, String nodeName) throws JsonProcessingException {
        XmlMapper xmlMapper = new XmlMapper();
        xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, false);
        JsonNode rootNode = xmlMapper.readTree(xml);
        List<JsonNode> values = rootNode.findValues(nodeName);
        //此处只保留第一条且需要做判空处理
        return values.get(0).asText();
    }

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部