一个小Demo阐释Dom解析处理的过程


import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.Attr;
import org.w3c.dom.NodeList;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
public class XmlParser
{   public static void main(String[] args)
            throws Exception
    {        xmlwriter();
    }
    public static void xmlparser()
            throws Exception
    {
        DocumentBuilderFactory xdf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = xdf.newDocumentBuilder();
        Document d = db.parse("C:\\A1\\customer.xml");
        NodeList nl = d.getElementsByTagName("customer");
        for (int i = 0; i < nl.getLength(); i++)
        {

            Element e = (Element) nl.item(i);
            Attr a = e.getAttributeNode("customerID");
            System.out.println(a.getNodeValue());
            NodeList nl1 = e.getElementsByTagName("customerName");
            System.out.println(nl1.item(0).getFirstChild().getNodeValue());
        }
    }
    public static void xmlwriter() throws Exception
    {
        DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
        DocumentBuilder db=dbf.newDocumentBuilder();
        Document d=db.parse("C:\\A1\\customer.xml");
        NodeList nl=d.getElementsByTagName("customerName");
        for(int i=0;i<nl.getLength();i++)
        {
           Element e=(Element) nl.item(i);
           System.out.println(e.getFirstChild().getNodeValue());
           e.getFirstChild().setNodeValue(e.getFirstChild().getNodeValue()+"111111111111111");
        }
        TransformerFactory tff=TransformerFactory.newInstance();
        Transformer tf=tff.newTransformer();
        tf.transform(new DOMSource(d),new StreamResult("c:\\aa.xml"));
}   }



运行:

DocumentBuiler db
Document d=db.parse(“具体文件路径”);
NodeList nl=d.getElementsByTagName(“节点名”)

你可能感兴趣的:(demo)