[Java]JDOM
漆雕安晏
2023-12-01
Read from XML File
public class DiskInfo {
private static DiskInfo instance = new DiskInfo();
private Element rootElt;
private HDInfo hdInfo = new HDInfo();
private DiskInfo() {
SAXBuilder sb = new SAXBuilder();
try {
Document doc = sb.build(this.getClass().getClassLoader().getResourceAsStream("disk-info.xml"));
// Document doc = sb.build(Thread.currentThread().getContextClassLoader().getResourceAsStream("disk-info.xml"));
rootElt = (Element)doc.getRootElement();
initDiskC();
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static DiskInfo getInstance() {
return instance;
}
private void initDiskC() {
try {
Element capacityElt = (Element)XPath.selectSingleNode(rootElt, "//HD/disk/capacity");
hdInfo.setCapacity(capacityElt.getText());
Element directoriesElt = (Element)XPath.selectSingleNode(rootElt, "//HD/disk/directories");
hdInfo.setDirectories(Integer.parseInt(directoriesElt.getText()));
Element filesElt = (Element)XPath.selectSingleNode(rootElt, "//HD/disk/files");
hdInfo.setFiles(Integer.parseInt(filesElt.getText()));
} catch (JDOMException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
System.out.println(DiskInfo.getInstance().hdInfo.toString());
}
}
Write to XML File
public class XMLWriter {
public static void main(String[] args) {
Element rootElt = new Element("company");
Element personElt = new Element("person");
Element nameElt = new Element("name");
nameElt.addContent("Tom");
Element ageElt = new Element("age");
ageElt.addContent("24");
personElt.addContent(nameElt);
personElt.addContent(ageElt);
rootElt.addContent(personElt);
Document doc = new Document(rootElt);
XMLOutputter out = new XMLOutputter();
String s = out.outputString(doc);
System.out.println(s);
}
}