java自带工具对象转xml,工具是jaxbContext,不废话,直接上代码
java对象
java
package com.configure.util;
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/7/5 10:48
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@XmlAccessorType(XmlAccessType.FIELD)
public class UserxxVO {
@XmlAttribute(name = "name")
private String userName;
@XmlValue
private String password;
}
java对象
java
package com.configure.util;
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 11:02
*/
@Data
@XmlRootElement(name = "resource")
@XmlAccessorType(XmlAccessType.FIELD)
public class ResourcexxVO {
@XmlElement(name = "string")
private List<UserxxVO> list;
}
生成xml代码
java
public static void main(String[] args) throws JAXBException {
List<UserxxVO> list = new ArrayList<>();
for (int i = 0; i < 3; i++) {
list.add(new UserxxVO("username"+i,"pass1123"));
}
ResourcexxVO resourcexxVO = new ResourcexxVO();
resourcexxVO.setList(list);
// JAXBContext jaxbContext = JAXBContext.newInstance(UserxxVO.class,ResourcexxVO.class);
JAXBContext jaxbContext = JAXBContext.newInstance(ResourcexxVO.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);
marshaller.setProperty(Marshaller.JAXB_FRAGMENT,true);
StringWriter stringWriter = new StringWriter();
stringWriter.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
marshaller.marshal(resourcexxVO,stringWriter);
System.out.println(stringWriter);
}