package Xmll;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* 解析xml
*
* @author Administrator
*
*/
public class Xml {
public Document document;
// 获得Document对象
public void getDocument() throws Exception {
// 获取解析器工厂
// 获得
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// 根据工厂获得解析器
DocumentBuilder builder = factory.newDocumentBuilder();
// 根据解析器获得Document
document = builder.parse("user.xml");
}
// 获取银行所有账户的id及姓名
public void showInfo() {
// 获取所有的<user>
NodeList users = document.getElementsByTagName("user");
// 获取每个<user>的id
for (int i = 0; i < users.getLength(); i++) {
Node userNode = users.item(i);
Element userEle=(Element)userNode;
System.out.print(userEle.getAttribute("id")+"--");
//获取每个<user>里面的子节点,找到其中的<name>
NodeList userChilds=userNode.getChildNodes();
for (int j = 0; j <userChilds.getLength(); j++) {
Node child=userChilds.item(j);
if(child.getNodeType()==Node.ELEMENT_NODE&&child.getNodeName().equals("name")){
Element nameEle=(Element)child;
System.out.println(nameEle.getTextContent());
}
}
}
}
//保存XML文件
public void saveXml(String path){
TransformerFactory tf=TransformerFactory.newInstance();
tf.setAttribute("indent-number", 4);
// Transformer tf1=factory.
}
// 增加一个银行账户
public void addUser() {
Element user=document.createElement("user");
user.setAttribute("id", "u4");
Element name=document.createElement("name");
name.setTextContent("王五");
Element cardID=document.createElement("cardID");
name.setTextContent("5522552");
Element money=document.createElement(" money");
name.setTextContent(" money");
user.appendChild(name);
user.appendChild(cardID);
user.appendChild(money);
document.getElementsByTagName("users").item(0).appendChild(user);
}
// 将所有的银行账户id修改
public void updateUser() {
}
// 删除某个账户信息
public void deleteUser() {
}
//
public static void main(String[] args) throws Exception{
Xml bk=new Xml();
bk.getDocument();
bk.addUser();
bk.showInfo();
}
}