zoukankan      html  css  js  c++  java
  • Java Dom对XML的解析和修改操作

       与Dom4J和JDom对XML的操作类似,JDK提供的JavaDom解析器用起来一样方便,在解析XML方面Java DOM甚至更甚前两者一筹!其不足之处在于对XML的增删改比较繁琐,特开篇介绍...

    1、XML文件如下:

    <?xml version="1.0"  encoding="UTF-8"?>
    <address-book>
        <contact id="01" type="家庭" >
            <name>张三</name>
            <address>黄山路666号</address>
            <city>阜阳</city>
            <province>安徽</province>
            <postalcode>236000</postalcode>
            <country>中国</country>
            <telephone>18056075816</telephone>
    </contact>
    <contact id="02" type="商务" >
            <name>李四</name>
            <address>望江西路888号</address>
            <city>合肥</city>
            <province>安徽</province>
            <postalcode>230091</postalcode>
            <country>中国</country>
            <telephone>13956921922</telephone>
    </contact>
    <contact id="03" type="同学" >
            <name>王五</name>
            <address>民主路3号</address>
            <city>贵港市</city>
            <province>广西</province>
            <postalcode>537111</postalcode>
            <country>中国</country>
            <telephone>13965131384</telephone>
    </contact>
    <address-book>
    


    2、与XML对应的域对象如下:

    public class Contact
    {
    	private String id;
    	private String type;
    	private String name;
    	private String address;
    	private String city;
    	private String privince;
    	private String postalcode;
    	private String country;
    	private String telephone;
    	
    	public Contact(String id, String type, String name, String address,
    			String city, String privince, String postalcode, String country,
    			String telephone)
    	{
    		this.id = id;
    		this.type = type;
    		this.name = name;
    		this.address = address;
    		this.city = city;
    		this.privince = privince;
    		this.postalcode = postalcode;
    		this.country = country;
    		this.telephone = telephone;
    	}
    	
    	
    	public Contact()
    	{
    		
    	}
    	
    	//省略Set Get方法
    	
    }


    3、解析XML的过程

    import java.util.ArrayList;
    import java.util.List;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.xpath.XPath;
    import javax.xml.xpath.XPathConstants;
    import javax.xml.xpath.XPathFactory;
    import org.w3c.dom.Document;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    
    public class ParseXML
    {
    	List<Contact> contacts = new ArrayList<Contact>();
    
    	public List<Contact> getContacts()
    	{
    		return contacts;
    	}
    
    	public ParseXML() throws Exception
    	{
    		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    		DocumentBuilder db = dbf.newDocumentBuilder();
    		Document doc = db.parse("YellowBook.xml");
    
    		XPathFactory xpf = XPathFactory.newInstance();
    		XPath xPath = xpf.newXPath();
    		NodeList nodes = (NodeList) xPath.evaluate("/address-book/contact", doc, XPathConstants.NODESET);
    		for(int i=0;i<nodes.getLength();i++)
    		{
    			Node node=nodes.item(i);
    			this.contacts.add(nodeToContact(node));
    		}
    	}
    	
    	public Contact nodeToContact(Node node) throws Exception
    	{
    		XPathFactory xpf = XPathFactory.newInstance();
    		XPath xPath = xpf.newXPath();
    		String id=(String) xPath.evaluate("@id", node,XPathConstants.STRING);
    		String type=(String) xPath.evaluate("@type", node,XPathConstants.STRING);
    		String name=(String) xPath.evaluate("name", node,XPathConstants.STRING);
    		String address=(String) xPath.evaluate("address", node,XPathConstants.STRING);
    		String city=(String) xPath.evaluate("city", node,XPathConstants.STRING);
    		String province=(String) xPath.evaluate("province", node,XPathConstants.STRING);
    		String postalcode=(String) xPath.evaluate("postalcode", node,XPathConstants.STRING);
    		String country=(String) xPath.evaluate("country", node,XPathConstants.STRING);
    		String telephone=(String) xPath.evaluate("telephone", node,XPathConstants.STRING);
    		Contact c=new Contact(id, type, name, address, city, province, postalcode, country, telephone);
    		return c;
    	}
    }
    


    4、对XML操作以及序列化的过程

    import java.io.FileOutputStream;
    import java.util.Scanner;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.OutputKeys;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    
    public class SerializeXML
    {
    	public void serializeXML(String id) throws Exception
    	{
    		Scanner sc=new Scanner(System.in);
    		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    		DocumentBuilder db = dbf.newDocumentBuilder();
    		Document doc = db.parse("YellowBook.xml");
    		
    		NodeList nodes=doc.getElementsByTagName("contact");
    		for(int i=0;i<nodes.getLength();i++)
    		{
    			Element e=(Element) nodes.item(i);
    			if(e.getAttribute("id").equals(id))
    			{
    				System.out.println("输入类型:");
    				String type=sc.nextLine();
    				e.setAttribute("type", type);
    				
    				NodeList childNodes=e.getChildNodes();
    				for(int j=0;j<childNodes.getLength();j++)
    				{
    					Node childNode=(Node) childNodes.item(j);
    					if(childNode.getNodeName().equals("name"))
    					{
    						System.out.println("输入姓名:");
    						String name=sc.nextLine();
    						childNode.setTextContent(name);
    					}
    				}
    			}
    		}
    		
    		TransformerFactory transformerFactory=TransformerFactory.newInstance();
    		Transformer transformer=transformerFactory.newTransformer();
    		DOMSource domSource=new DOMSource(doc);
    		transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
    		StreamResult result=new StreamResult(new FileOutputStream("YellowBook.xml"));
    		transformer.transform(domSource, result);
    	}
    }
    


    5、涉及业务逻辑的处理

    import java.util.List;
    
    public class ContactService
    {
    	public Contact findById(String id) throws Exception
    	{
    		ParseXML xml=new ParseXML();
    		List<Contact> contacts=xml.getContacts();
    		Contact con=new Contact();
    		for(Contact c:contacts)
    		{
    			if(c.getId().equals(id))
    			{
    				con=c;
    			}
    		}
    		return con;
    	}
    	
    	public void updateById(String id) throws Exception
    	{
    		SerializeXML serializeXML=new SerializeXML();
    		serializeXML.serializeXML(id);
    	}
    }


    6、测试

    public class Main
    {
    	public static void main(String[] args) throws Exception
    	{
    		ContactService contactDao=new ContactService();
    		Contact con=contactDao.findById("01");
    		System.out.println(con.getName());
    		
    		contactDao.updateById("02");
    	}
    }
    




  • 相关阅读:
    SDUT 2109 找女朋友
    Instant Complexity(模拟,递归)
    Lucky and Good Months by Gregorian Calendar(模拟)
    Wall(Graham算法)
    Beauty Contest(graham求凸包算法)
    A Round Peg in a Ground Hole(判断是否是凸包,点是否在凸包内,圆与多边形的关系)
    Pie(二分)
    Expanding Rods(二分)
    Fishnet(计算几何)
    Building a Space Station(kruskal,说好的数论呢)
  • 原文地址:https://www.cnblogs.com/xmc0551/p/5645570.html
Copyright © 2011-2022 走看看