java使用JAXBContext解析xml。
垃圾程序员才一会废话,直接不解释,上代码!
javabean对象
package com.configure.vo;
import com.haier.configure.dto.ResourceCodeTextDTO;
import lombok.Data;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;
/**
* @author A2001111
* @date 2024/7/5 13:14
*/
@Data
@XmlRootElement(name = "resources")
@XmlAccessorType(XmlAccessType.FIELD)
public class I18nXmlResourcesVO {
@XmlElement(name = "string")
private List<ResourceCodeTextDTO> texts;
}
java对象
package com.configure.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlValue;
/**
* @author A2001111
* @date 2024/1/3117:06
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@XmlAccessorType(XmlAccessType.FIELD)
public class ResourceCodeTextDTO {
/**
* 资源code
*/
@XmlAttribute(name = "name")
private String code;
/**
* 资源文本
*/
@XmlValue
private String text;
}
解析代码
private List<ResourceCodeTextDTO> parseXmlContent(String content){
if (StringUtils.isBlank(content)) {
return null;
}
try {
JAXBContext jaxbContext = JAXBContext.newInstance(I18nXmlResourcesVO.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
StringReader stringReader = new StringReader(content);
I18nXmlResourcesVO xmlResourcesVO = (I18nXmlResourcesVO) unmarshaller.unmarshal(stringReader);
if (null == xmlResourcesVO) {
return null;
}
return xmlResourcesVO.getTexts();
} catch (Exception e) {
log.error("多语言解析xml内容失败:[{}]",e.getMessage());
throw new BizException(e.getMessage());
}
}