Java的Document类是org.w3c.dom包中的一个接口,它代表了XML文档的根节点。它定义了操作XML文档的方法和属性。
Document类的用法包括:
示例代码:
File xmlFile = new File("path/to/xml/file.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(xmlFile);
示例代码:
Element rootElement = document.createElement("root");
document.appendChild(rootElement);
Element childElement = document.createElement("child");
rootElement.appendChild(childElement);
示例代码:
NodeList nodeList = document.getElementsByTagName("elementName");
Element element = (Element) nodeList.item(0);
Element elementById = document.getElementById("elementId");
示例代码:
element.setAttribute("attributeName", "attributeValue");
element.setTextContent("text content");
示例代码:
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(new File("path/to/output.xml"));
transformer.transform(source, result);
通过使用Document类,可以方便地创建、操作和保存XML文档。