1 不带命名空间的文档
创建空文档
Document doc = builder.newDocument();
构建元素
Element rootElement = doc.createElement(rootName);
Element childElement = doc.createElement(childName);
构建文本节点
Text textNode = doc.createTextNode(textContents);
设置元素属性
rootElement.setAttribute(name, value);
添加给文档
doc.appendChild(rootElement);
rootElement.appendChild(childElement);
childElement.appendChild(textNode);
2 带命名空间的文档
创建命名空间感知的生成器
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
builder = factory.newDocumentBuilder();
使用 createElementNS 创建节点
String namespace = "";
Element rootElement = doc.createElementNS(namespace,"svg:svg");
//结果:<svg:svg xmlns:svg="">
设置元素属性
rootElement.setAttributeNS(namespace, qualifiedName, value);
3 DOM树写出文档
3.1 XSLT API
DOM 树写出到输出流,最容易的方式是使用 XSLT API。
Transformer t = TransformerFactory.newInstance().newTransformer();
//将DOCTYPE节点纳入输出
t.setOutputProperty(OutPutKeys.DOCTYPE_SYSTEM, systemIdentifier);
t.setOutputProperty(OutPutKeys.DOCTYPE_PUBLIC, publicIdentifier);
//设置缩进
t.setOutputProperty(OutPutKeys.INDENT, "YES");
t.setOutputProperty(OutPutKeys.METHOD, "xml");
t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
//转换到文档
t.transform(new DOMSorce(doc),new StreamResult(new FileOutputStream(file)));
3.2 LSSerializer 接口
DOMImplementation impl = doc.getImplementation();
DOMImplementationLS implLS = (DOMImplementationLS)impl.getFeature("LS","3.0");
lssERIALIZER SER = implLS.createLSSerializer();
//设置空格和换行
ser.getDomConfig().setParameter("format-pretty-print", true);
//转为字符串
String str = ser.writeToString(doc);
写入文件
LSOutput out = implLS.createLSOutput();
out.serEncoding("UTF-8");
out.setByteStream(Files.newOutputStream(path));
ser.write(doc, out);
4 StAX 写出 XML 文档
XMLOutputFactory factory = XMLOutputFactory.newInstance();
XMLStreamWriter writer = factory.createXMLStreamWriter(out);
//产生XML文件头
writer.writerStartDocument();
//添加属性
writer.writeAttribute(name, value);
//新子节点
writer.writeStartElemrnt()
//写出字符
writer.writeCharacters(text);
//关闭子节点
writer.writerEndElement();
//写出没有子节点的元素
writer.writerEmptyElement(name);
//文档结尾
writer.writerEndDocument();