xml 充当数据库使用


Xml
1.充当数据库 2.在框架中充当配置文件
Extendsible Markup Language   缩写XML 使用简单的标记来描述数据
 格式良好的xml文档文档需要满足:
必须有xml声明语句
必须有且仅有一个根元素
标签大小写敏感
属性值用双引号
标签成对
元素正确嵌套

<?xml version="1.0" encoding="UTF-8"?>
<books>
	<book id="bk101">
		<name>时间简史</name>
		<author>霍金</author>
		<price>60</price>
	</book>
	<book id="bk102">
		<name>史记</name>
		<author>司马迁</author>
		<price>85</price>
	</book>
	<book id="bk103">
		<name>三国演义</name>
		<author>施耐庵</author>
		<price>80</price>
	</book>
	<book id="bk104">
		<name>西游记</name>
		<author>罗贯中</author>
		<price>89</price>
	</book>
</books>
package com.entry;

import java.io.IOException;
import java.lang.annotation.Documented;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.w3c.dom.Node;

public class test {

	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		// 把文件内容加载到内存中
		Document doc = db.parse("src/book.xml");
		// 获取所有子节点
		NodeList roots = doc.getChildNodes();
		//获取根节点
		Node root = roots.item(0);
		//获取根节点的所有子节点(所有的book节点)
		NodeList books = root.getChildNodes();
		//遍历所有book节点,查找每个book节点的子节点
		for (int i = 0; i < books.getLength(); i++) {
			Node book = books.item(i);
			//获取book子节点(name,author,price,...)
			NodeList items = book.getChildNodes();
			//历所有book子节点
			for (int j = 0; j < items.getLength(); j++) {
				//获取节点
				Node item = items.item(j);
				if (item.getNodeName().equals("name")) {
					                               //获取标签的内容
					System.out.println("书名:" + item.getTextContent());
				}
				if (item.getNodeName().equals("author")) {
					System.out.println("作者:" + item.getTextContent());
				}
				if (item.getNodeName().equals("price")) {
					System.out.println("价格:" + item.getTextContent()+"¥");
				}
			}
			System.out.println();
		}
	}

}

猜你喜欢

转载自blog.csdn.net/liujucai/article/details/81316897
今日推荐