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文檔。