XML

XML

可擴展的標記語言
作用:1、存儲、交換數據
	   2、配置
1、語言規範:
1)、必須有XML文檔聲明
2)、必須有且僅有一個根元素
3)、嚴格區分大小寫
4)、屬性值用引號(雙引號或單引號):等號分開的名稱-值對;在一個元素上,相同2的屬性只能出現一次
5)、標記成對
6)、空標記關閉
7)、元素正確嵌套
2、元素命名規則
1)、名稱中可以包含字母、數字或者其他可見字符;
2)、名稱不能以數字開頭;
3)、不能以 XML/xml/Xml…開頭;
4)、名稱中不能含空格;
5)、名稱中不能含冒號(注:冒號留給命名空間使用)

XML解析:

1、DOM解析
public static void createXml() throws Exception{
    //獲取解析器工廠
    DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
    //獲取解析器
    DocumentBuilder builder=factory.newDocumentBuilder();
    //創建文檔
    Document doc=builder.newDocument();
    //創建元素、設置關係
    Element root=doc.createElement("people");
    Element person=doc.createElement("person");
    Element name=doc.createElement("name");
    Element age=doc.createElement("age");
    name.appendChild(doc.createTextNode("shsxt"));
    age.appendChild(doc.createTextNode("10"));
    doc.appendChild(root);
    root.appendChild(person);
    person.appendChild(name);
    person.appendChild(age);
    //寫出去
    // 獲得變壓器工廠
    TransformerFactory tsf=TransformerFactory.newInstance();
    Transformer ts=tsf.newTransformer();
    //設置編碼上海尚學堂智能科技有限公司
    www.shsxt.com
    ts.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    //創建帶有DOM節點的新輸入源,充當轉換Source樹的持有者
    DOMSource source=new DOMSource(doc);
    //充當轉換結果的持有者
    File file=new File("src/output.xml");
    StreamResult result=new StreamResult(file);
    ts.transform(source, result);
    }

2、DOM4J解析
//解析
public class Dom4JReader {	
	public static void main(String[] args) throws Exception {
		// 1、得到要解析的文件對象
		File file = new File("src/test.xml");
		// 2、得到解析器
		SAXReader reader = new SAXReader();
		// 3、通過解析器將文件對象轉換成Document對象
		Document document = reader.read(file);
		// 4、得到當前文檔對象的根節點
		Element root = document.getRootElement();
		// 5、得到 根節點的所有子節點,返回迭代器
		Iterator<Element> iterator = root.elementIterator();
		// 6、遍歷,得到每一個子節點的名稱和值
		while(iterator.hasNext()) {
			Element el = iterator.next();
			System.out.println(el.getName());
			System.out.println(el.getText());
		}
	}
}
//創建
public class Dom4JWriter {
	public static void main(String[] args) throws Exception {
		// 使用DocumentHelper來創建 Document對象
		Document document = DocumentHelper.createDocument();
		// 創建元素並設置關係
		Element person = document.addElement("person");
		Element name = person.addElement("name");
		Element age = person.addElement("age");
		// 設置文本
		name.setText("shsxt");
		age.setText("10");
		// 創建格式化輸出器
		OutputFormat of = OutputFormat.createPrettyPrint();
		of.setEncoding("utf-8");
		// 輸出到文件
		File file = new File("src/outputdom4j.xml");
		XMLWriter writer = new XMLWriter(new FileOutputStream(new File(file.getAbsolutePath())),of);
		// 寫出
		writer.write(document);
		writer.flush();
		writer.close();	
	}
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章