在 Java 中将字符串 XML 片段转换为文档节点
在Java中,如何转换表示XML片段的字符串以插入到XML文档中?
例如:
String newNode = "<node>value</node>"; // Convert this to XML
然后将此节点作为给定节点的子节点插入 org.w3c.dom.Document 中?
在Java中,如何转换表示XML片段的字符串以插入到XML文档中?
例如:
String newNode = "<node>value</node>"; // Convert this to XML
然后将此节点作为给定节点的子节点插入 org.w3c.dom.Document 中?
Element node = DocumentBuilderFactory
.newInstance()
.newDocumentBuilder()
.parse(new ByteArrayInputStream("<node>value</node>".getBytes()))
.getDocumentElement();
/**
* @param docBuilder
* the parser
* @param parent
* node to add fragment to
* @param fragment
* a well formed XML fragment
*/
public static void appendXmlFragment(
DocumentBuilder docBuilder, Node parent,
String fragment) throws IOException, SAXException {
Document doc = parent.getOwnerDocument();
Node fragmentNode = docBuilder.parse(
new InputSource(new StringReader(fragment)))
.getDocumentElement();
fragmentNode = doc.importNode(fragmentNode, true);
parent.appendChild(fragmentNode);
}