IXJ A001
public class Main {
static Document doc;
static File f = new File("src\\set4\\doctorlist.xml");
public static void main(String[] args) {
createDocuemntXML();
try {
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Node doc = db.parse("src\\set4\\doctorlist.xml");
readDocumentXML(doc);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
private static void readDocumentXML(Node doc) {
try {
if (doc.getNodeName().equals("doctor")) {
String str = doc.getAttributes().getNamedItem("DoctorID").getNodeValue();
System.out.println("Doctor Id is :" + str);
}
if (doc.getNodeName().equals("Name")) {
System.out.println("\tDoctor Name is :" + doc.getTextContent());
}
NodeList children = doc.getChildNodes();
int i = 0;
while (i < children.getLength()) {
readDocumentXML(children.item(i++));
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
private static void createDocuemntXML() {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.newDocument();
Element root = doc.createElement("DoctorList");
Element doctor1 = doc.createElement("doctor");
Attr doctorid1 = doc.createAttribute("DoctorID");
doctorid1.setValue("1");
doctor1.setAttributeNode(doctorid1);
Element name1 = doc.createElement("Name");
Text namevalue1 = doc.createTextNode("Long");
name1.appendChild(namevalue1);
doctor1.appendChild(name1);
root.appendChild(doctor1);
Element doctor2 = doc.createElement("doctor");
Attr doctorid2 = doc.createAttribute("DoctorID");
doctorid2.setValue("2");
doctor2.setAttributeNode(doctorid2);
Element name2 = doc.createElement("Name");
Text namevalue2 = doc.createTextNode("hai");
name2.appendChild(namevalue2);
doctor2.appendChild(name2);
root.appendChild(doctor2);
doc.appendChild(root);
Source source = new DOMSource(doc);
Result result = new StreamResult(f);
TransformerFactory tff = TransformerFactory.newInstance();
Transformer tf = tff.newTransformer();
tf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
tf.setOutputProperty(OutputKeys.INDENT, "yes");
tf.transform(source, result);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
Bạn đang đọc truyện trên: AzTruyen.Top