在Java中,要将XML解析为String而不是文件,可以使用Java的内置库JAXB(Java Architecture for XML Binding)。JAXB允许将Java对象和XML文档之间进行转换,以便可以将Java对象序列化为XML字符串,或者将XML字符串反序列化为Java对象。
以下是一个简单的示例,演示如何将Java对象序列化为XML字符串:
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;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.StringWriter;
public class XmlStringExample {
public static void main(String[] args) {
Person person = new Person("John Doe", 30);
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);
String xmlString = stringWriter.toString();
System.out.println(xmlString);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
运行上述代码,将输出以下XML字符串:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><person>
<age>30</age>
<name>John Doe</name>
</person>
这样,您就可以将Java对象序列化为XML字符串,而不是将其写入文件。
领取专属 10元无门槛券
手把手带您无忧上云