import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.concurrent.ConcurrentHashMap;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* XML 工具类
*/
public class XMLUtils {
public static ConcurrentHashMap<Class<?>, JAXBContext> contextMap = new ConcurrentHashMap<>();
public static <T> String objectToXML(T object) {
StringWriter stringWriter = null;
try {
JAXBContext jaxbContext = getContext(object.getClass());
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
stringWriter = new StringWriter();
marshaller.marshal(object, stringWriter);
return stringWriter.toString();
} catch (JAXBException e) {
throw new IllegalArgumentException(e);
} finally {
if (stringWriter != null) {
try {
stringWriter.close();
} catch (IOException ignore) {}
}
}
}
@SuppressWarnings("unchecked")
public static <T> T xmlToObject(String xml, Class<T> clazz) {
StringReader stringReader = null;
try {
JAXBContext jaxbContext = getContext(clazz);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
stringReader = new StringReader(xml);
return (T) unmarshaller.unmarshal(stringReader);
} catch (JAXBException e) {
throw new IllegalArgumentException(e);
} finally {
if (stringReader != null) stringReader.close();
}
}
private static JAXBContext getContext(Class<?> clazz) {
return contextMap.computeIfAbsent(
clazz,
innerClass -> {
try {
return JAXBContext.newInstance(innerClass);
} catch (JAXBException e) {
throw new IllegalArgumentException(e);
}
}
);
}
public static String getNodeContent(String xml, String nodeName) {
try {
DocumentBuilder builder = DocumentBuilderFactory
.newInstance()
.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xml)));
NodeList nodeList = document.getElementsByTagName(nodeName);
return nodeList.getLength() > 0
? nodeList.item(0).getTextContent()
: null;
} catch (ParserConfigurationException | SAXException | IOException e) {
throw new IllegalArgumentException(e);
}
}
public static String getDocumentAsString(Document document) {
String output = "";
try {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(document), new StreamResult(writer));
output = writer.getBuffer().toString();
} catch (Exception e) {
LoggerUtil.error("getDocumentAsString-解析xml发生异常:", e);
}
return output;
}
}
Java - xml工具类
最新推荐文章于 2024-06-18 15:00:50 发布