element的方法里没有这样的功能,只能通过格式化等方式获取。
从老外那复制了一个,只依赖jdk本身,反正好使。
package com.xxxx;
import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory;
import org.apache.log4j.Logger; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.bootstrap.DOMImplementationRegistry; import org.w3c.dom.ls.DOMImplementationLS; import org.w3c.dom.ls.LSSerializer;
public class BaseClient {
static Logger logger = Logger.getLogger(BaseClient.class);
private static LSSerializer domWriter;
static { DOMImplementationRegistry registry; try { registry = DOMImplementationRegistry.newInstance(); DOMImplementationLS impl = (DOMImplementationLS) registry .getDOMImplementation("LS"); domWriter = impl.createLSSerializer();
domWriter.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE); // 是否格式化 domWriter.getDomConfig().setParameter("xml-declaration", false); // 保留XML声明行
} catch (Exception e) { logger.error("domWriter初始化出错", e); } }
/** * 获取XML节点的XML内容. * @param node * @return */ protected String getNodeXml(Node node) { return domWriter.writeToString(node); } }
|