1:DTD規範html
dtd規範:規範xml格式,規定xml標籤及屬性名稱。java
JAVA源碼:mysql
<?xml version="1.0" encoding="UTF-8"?>
//DTD規定
<!ELEMENT books (book*)>
<!DOCTYPE book [
<!ATTLIST book id CDATA #IMPLIED> //id規定
<!ELEMENT book (name,autour,price)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT autour (#PCDATA)>
<!ELEMENT price (#PCDATA)>
]>sql
2:DomFactory解析oracle
JAVA源碼:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse("books.xml");
NodeList list = doc.getElementsByTagName("book");
for(int i = 0 ;i<list.getLength();i++){
NodeList lists = list.item(i).getChildNodes();
//獲得屬性
Element ele = (Element) lists;
System.out.println(ele.getAttribute("id").toString());
for(int j = 0 ;j<lists.getLength();j++){
//使用判斷獲得屬性
if(lists.item(j).getNodeName().equals("name")){
//lists.item(j).setNodeValue("語文");
//lists.item(j).setTextContent("語文");
System.out.println("圖書名字是:"+lists.item(j).getTextContent());
}
}
}
}ui
3:Dom4j解析編碼
JAVA源碼:
File file = new File("books.xml");
SAXReader saxReader = new SAXReader();
Document doc = saxReader.read(file);
Element ele1 = doc.getRootElement();
Iterator ite1 = ele1.elementIterator();
while(ite1.hasNext()){
Element ele2 = (Element)ite1.next();
Iterator ite2 = ele2.elementIterator();
System.out.println(ele2.attribute("id").getValue());
while(ite2.hasNext()){
Element ele3 = (Element)ite2.next();
if(ele3.getName().equals("name")){
System.out.println("圖書名字是:"+ele3.getText());
}
}
}
}orm
4:xml文件修改xml
//保存文檔(DomFactory讀xml文件)
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
DOMSource ds = new DOMSource(doc);
//設置編碼格式
t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
StreamResult rs = new StreamResult(new FileOutputStream("books.xml"));
//轉換成文檔
t.transform(ds, rs);htm
附:xml文件內容,文件名稱book.xml <?xml version="1.0" encoding="UTF-8"?> //DTD規定 <!ELEMENT books (book*)> <!DOCTYPE book [ <!ATTLIST book id CDATA #IMPLIED> //id規定 <!ELEMENT book (name,autour,price)> <!ELEMENT name (#PCDATA)> <!ELEMENT autour (#PCDATA)> <!ELEMENT price (#PCDATA)> ]> <!—XML內容 --> <books> <book id="0001"> <name>java基礎</name> <autour>青哥</autour> <price>20.5</price> </book> <book id="0002"> <name>html基礎</name> <autour>趙五</autour> <price>32.5</price> </book> <book id="0003"> <name>oracle基礎</name> <autour>小陳</autour> <price>32.0</price> </book> <book id="0004"> <name>mysql基礎</name> <autour>張三</autour> <price>15</price> </book> </books>