当然有!在Java中,您可以使用JAXB(Java Architecture for XML Binding)库将XML对象转换回String。JAXB是一个标准的Java库,用于将Java对象转换为XML格式,反之亦然。以下是一个简单的示例,说明如何将XML对象转换回Java中的String。
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Person {
private String name;
private int age;
public Person() {}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@XmlElement
public void setName(String name) {
this.name = name;
}
@XmlElement
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.StringWriter;
public class XmlConverter {
public static String convertToXml(Person person) {
String xmlString = null;
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Person.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter stringWriter = new StringWriter();
marshaller.marshal(person, stringWriter);
xmlString = stringWriter.toString();
} catch (JAXBException e) {
e.printStackTrace();
}
return xmlString;
}
}
public static void main(String[] args) {
Person person = new Person("John Doe", 30);
String xmlString = XmlConverter.convertToXml(person);
System.out.println(xmlString);
}
运行上述代码后,您将看到以下XML字符串:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><person>
<name>John Doe</name>
<age>30</age>
</person>
这就是将XML对象转换回Java中的String的简单方法。希望这对您有所帮助!
领取专属 10元无门槛券
手把手带您无忧上云