如何将XML节点从<ns0:Request>
更新为<ns1:Request xmlns:ns1="with some URL">
在Java中使用DOM解析器。
我不想使用replaceAll()
方法。
答案 0 :(得分:0)
您可以使用Node.replaceChild(Node, Node)
方法执行以下操作:
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Demo {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
// Create original document
Document document = db.newDocument();
Element root = document.createElementNS("urn:FOO", "ns0:Root");
document.appendChild(root);
Element request = document.createElementNS("urn:FOO", "ns0:Request");
root.appendChild(request);
// Create new Request element.
Element newRequest = document.createElementNS("urn:BAR", "ns1:Request");
// Replace Request element
root.replaceChild(newRequest, request);
// Output the new document
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(System.out);
t.transform(source, result);
}
}