java 解析 xml 字符串转换为实体,实体转换为 xml 字符串
1. XmlCommonUtil工具类代码如下:
c
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
/**
* XmlCommonUtil类用于XML字符串和对象之间的转换以及读取文件操作
*/
public class XmlCommonUtil {
/**
* 将XML字符串转换为指定类的对象
*
* @param xml XML字符串
* @param clazz 目标类的Class对象
* @return 转换后的对象
*/
public static Object convertXmlStrToObject(String xml, Class clazz) throws Exception {
JAXBContext context = JAXBContext.newInstance(clazz);
Unmarshaller unmarshaller = context.createUnmarshaller();
StringReader reader = new StringReader(xml);
return unmarshaller.unmarshal(reader);
}
/**
* 将实体对象转换为XML字符串
*
* @param obj 实体对象
* @return 转换后的字符串
*/
public static String convertObjectToXml(Object obj) throws Exception {
StringWriter sw = new StringWriter();
JAXBContext context = JAXBContext.newInstance(obj.getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(obj, sw);
return sw.toString();
}
}
2. 模拟资源文件数据SqlList.xml:
c
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<sqls>
<sql>
SELECT 1
WHERE 1 = 1
</sql>
<sql>
SELECT 2
WHERE 2 = 2
</sql>
</sqls>
3. 实体类SqlXml代码如下:
c
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* SqlXml类用于表示XML中的sql元素
*/
@XmlRootElement(name = "sqls")
@XmlType(propOrder = {"sql"})
public class SqlXml {
private List<String> sql;
@XmlElement(name = "sql")
public List<String> getSql() {
return sql;
}
public void setSql(List<String> sql) {
this.sql = sql;
}
@Override
public String toString() {
return "SqlXml{" +
"sql=" + sql +
'}';
}
}
4. main方法代码测试:
c
public static void main(String[] args) throws Exception{
// 读取指定文件中的XML内容
String xmlStr = readFile("sql/SqlList.xml");
// 将XML字符串转换为SqlXml对象
SqlXml sqlXml = (SqlXml)convertXmlStrToObject(xmlStr, SqlXml.class);
System.out.println(sqlXml);
// 将SqlXml对象转换为XML字符串
xmlStr = convertObjectToXml(sqlXml);
System.out.println(xmlStr);
}
/**
* 读取指定文件并返回文件内容
*
* @param file 文件路径
* @return 文件内容字符串
*/
public static String readFile(String file) {
StringBuffer sb = null;
try {
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(file);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
sb = new StringBuffer();
String line = "";
while ((line = bufferedReader.readLine()) != null) {
sb.append(line + "\r\n");
}
bufferedReader.close();
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
5. 执行结果:
c
SqlXml{sql=[
SELECT 1
WHERE 1 = 1
,
SELECT 2
WHERE 2 = 2
]}
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<sqls>
<sql>
SELECT 1
WHERE 1 = 1
</sql>
<sql>
SELECT 2
WHERE 2 = 2
</sql>
</sqls>
Process finished with exit code 0