dom解析xml文档的步骤

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了dom解析xml文档的步骤相关的知识,希望对你有一定的参考价值。

包括增加,删除,查询,主方法测式方法,下面有xml文档,记得导入jdom.jar
步骤是:
1、建立DocumentBuilderFactory
2、建立DocumentBuilder
3、解析xml文档
4、操作xml文档
5、建立TransformerFactory
6、建立Transformer
7、保存修改后的xml文档
下边是一个例子,希望可以帮到你
import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Attr;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class Company

String fileXMLName;

public Company(String fileXMLName)
super();
this.fileXMLName = fileXMLName;


public void showList()
try
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db=dbf.newDocumentBuilder();

Document doc=db.parse(this.fileXMLName);
NodeList n1=doc.getElementsByTagName("雇员");
for(int i=0;i<n1.getLength();i++)
Element guyuan=(Element)n1.item(i);
Attr bumen=guyuan.getAttributeNode("部门");
Attr quanzhi=guyuan.getAttributeNode("全职");
System.out.print("雇员"+(i+1));
if(bumen!=null)
System.out.println("部门:"+bumen.getValue());

if(quanzhi!=null)
System.out.println("全职:"+quanzhi.getValue());

NodeList xingming=guyuan.getElementsByTagName("姓名");
System.out.println("姓名:"+xingming.item(0).getFirstChild().getNodeValue());
NodeList gudate=guyuan.getElementsByTagName("雇佣日期");
System.out.println("雇佣日期:"+gudate.item(0).getFirstChild().getNodeValue());
NodeList qingdan=guyuan.getElementsByTagName("项目清单");
NodeList xiangmu=((Element)qingdan.item(0)).getElementsByTagName("项目");
for(int j=0;j<xiangmu.getLength();j++)
Element xiangmu2=(Element)xiangmu.item(j);
NodeList chanping=xiangmu2.getElementsByTagName("产品");
NodeList jiage=xiangmu2.getElementsByTagName("价格");
System.out.println("项目"+(j+1)+"产品:"+chanping.item(0).getFirstChild().getNodeValue());
System.out.println("项目"+(j+1)+"产品:"+jiage.item(0).getFirstChild().getNodeValue());


catch (DOMException e)
// TODO Auto-generated catch block
e.printStackTrace();
catch (ParserConfigurationException e)
// TODO Auto-generated catch block
e.printStackTrace();
catch (SAXException e)
// TODO Auto-generated catch block
e.printStackTrace();
catch (IOException e)
// TODO Auto-generated catch block
e.printStackTrace();


public void CreateOne(String chanping,String jiage)
try
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db=dbf.newDocumentBuilder();
Document doc=db.parse(this.fileXMLName);
NodeList xingming=doc.getElementsByTagName("姓名");
Element xingming1=null;
for(int i=0;i<xingming.getLength();i++)
xingming1=(Element)xingming.item(i);
String name=xingming1.getFirstChild().getNodeValue();
if(name.equals("王权"))
Element guyuan=(Element)xingming1.getParentNode();
NodeList qingdan=guyuan.getElementsByTagName("项目清单");
Element qingdan1=(Element)qingdan.item(0);
Element xiangmu=doc.createElement("项目");
Element chan=doc.createElement("产品");
Element jia=doc.createElement("价格");
chan.appendChild(doc.createTextNode(chanping));
jia.appendChild(doc.createTextNode(jiage));
xiangmu.appendChild(chan);
xiangmu.appendChild(jia);
qingdan1.appendChild(xiangmu);
TransformerFactory tf=TransformerFactory.newInstance();
Transformer tr=tf.newTransformer();
tr.transform(new DOMSource(doc), new StreamResult(new File("newcompany.xml")));
break;



catch (DOMException e)
// TODO Auto-generated catch block
e.printStackTrace();
catch (TransformerConfigurationException e)
// TODO Auto-generated catch block
e.printStackTrace();
catch (ParserConfigurationException e)
// TODO Auto-generated catch block
e.printStackTrace();
catch (SAXException e)
// TODO Auto-generated catch block
e.printStackTrace();
catch (IOException e)
// TODO Auto-generated catch block
e.printStackTrace();
catch (TransformerFactoryConfigurationError e)
// TODO Auto-generated catch block
e.printStackTrace();
catch (TransformerException e)
// TODO Auto-generated catch block
e.printStackTrace();



public void deleteone(String bumen)

try
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db=dbf.newDocumentBuilder();
Document doc=db.parse(this.fileXMLName);
NodeList gongsis=doc.getElementsByTagName("公司");
Element gongsi=(Element)gongsis.item(0);
NodeList guyuans=doc.getElementsByTagName("雇员");
Element guyuan=null;
for(int i=0;i<guyuans.getLength();i++)
guyuan=(Element)guyuans.item(i);
Attr bumens=guyuan.getAttributeNode("部门");
if((bumens!=null)&&(bumens.getValue().equals(bumen)))
gongsi.removeChild(guyuan);


TransformerFactory tf=TransformerFactory.newInstance();
Transformer tr=tf.newTransformer();
tr.transform(new DOMSource(doc), new StreamResult(new File("newcompany.xml")));
catch (DOMException e)
// TODO Auto-generated catch block
e.printStackTrace();
catch (TransformerConfigurationException e)
// TODO Auto-generated catch block
e.printStackTrace();
catch (ParserConfigurationException e)
// TODO Auto-generated catch block
e.printStackTrace();
catch (SAXException e)
// TODO Auto-generated catch block
e.printStackTrace();
catch (IOException e)
// TODO Auto-generated catch block
e.printStackTrace();
catch (TransformerFactoryConfigurationError e)
// TODO Auto-generated catch block
e.printStackTrace();
catch (TransformerException e)
// TODO Auto-generated catch block
e.printStackTrace();



public static void main(String[] args)
// TODO Auto-generated method stub

Company com=new Company("newcompany.xml");
com.showList();
// com.CreateOne("液晶显示器", "200");
// Company com1=new Company("newcompany.xml");
// com1.showList();
com.deleteone("客服部");
Company com2=new Company("newcompany.xml");
com2.showList();




xml文档格式
<?xml version="1.0" encoding="UTF-8"?><!--内部定义--><公司>
<雇员 全职="是" 部门="市场部">
<姓名>李东</姓名>
<雇佣日期>2005-01-15</雇佣日期>
<项目清单 数量="2">
<项目>
<产品>打印机</产品>
<价格>$111.00</价格>
</项目>
<项目>
<产品>笔记本</产品>
<价格>$9897.00</价格>
</项目>
</项目清单>
</雇员>
</公司>
参考技术A package com.mty95190.cn;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

public class Dom4jWriter

public void createXml(String fileName,String txtName)

Document document =DocumentHelper.createDocument();
Element root = document.addElement("root");
Element head = root.addElement("head");
Element type = head.addAttribute("type", "12");
Element code = head.addAttribute("code","cwb");
Element cwb = head.addElement("cwb");
cwb.setText("我是第一个");
Element zyw = head.addElement("zyw");
zyw.setText("你是第二个");
Element bb = cwb.addElement("bb");
bb.setText("我是你的gg");
Element mm = zyw.addElement("mm");
mm.setText("我是你的mm");

try
Writer fileWriter = new FileWriter(fileName);
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter xmlWriter = new XMLWriter(fileWriter,format);
xmlWriter.write(document);
xmlWriter.close();

catch (IOException e)
// TODO Auto-generated catch block
e.printStackTrace();



public static void main(String args[])
Dom4jWriter aa = new Dom4jWriter();
aa.createXml("D://aa.xml", "aa.txt");

xml解析

DOM把XML文映射成一个倒挂的树.
使用DOM解析XML文档的步骤:
(1)创建解析器工厂对象
(2)由解析器工厂对象创建解析器对象
(3)由解析器对象对指定XML文件进行解析,构建相应DOM树,创建Document对象
(4)以Document对象为起点对DOM树的节点进行增删改查操作。

//xml代码:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Pet [
<!ELEMENT pet (dogs,cat)>
<!ELEMENT dogs (dog*)>
<!ELEMENT dog (name,age,sex)>
<!ATTLIST dog id CDATA #REQUIRED>
<!ELEMENT cat (name,age,sex)>
]>
<pet>
  <dogs>
    <dog id="1">
      <name>aa</name>
      <age>10</age>
      <sex>10</sex>
    </dog>
    <dog id="2">
      <name>bb</name>
      <age>20</age>
      <sex>20</sex>
    </dog>
  </dogs>
  <cat>
    <name>kitty</name>
    <age>5</age>
    <sex>男</sex>
  </cat>
</pet>


//xml解析代码:
package Test;

import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class Pet{
  public static void main(String[] args){
    DocumentBuilderFactory dbf= DocumentBuilderFactory.newInstance();
    try {
      DocumentBuilder db=dbf.newDocumentBuilder();
      Document document=db.parse("src/Test/Pet.xml");
      NodeList dogList=document.getElementsByTagName("dog");
      System.out.println("一共有"+dogList.getLength()+"只狗狗");
      for(int i=0;i<dogList.getLength();i++){
        Node dog=dogList.item(i);
        Element elem=(Element)dog; (方:将node转化成element)
        String id=elem.getAttribute("id");
        System.out.println(id);
        for(Node node=elem.getFirstChild();node!=null;node=node.getNextSibling()){
          if(node.getNodeType()==Node.ELEMENT_NODE){
            String name=node.getNodeName();
            String value=node.getFirstChild().getNodeValue();
            System.out.println(name+":"+value);
          }
        }
      }
    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    } catch (SAXException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

 

//程序运行结果:
一共有2只狗狗
1
name:aa
age:10
sex:10
2
name:bb
age:20
sex:20

以上是关于dom解析xml文档的步骤的主要内容,如果未能解决你的问题,请参考以下文章

JAva使用DOM读取XML数据(解析)

xml学习

Java web——xml文件读取的解析方式(DOM和SAX)

DOM解析器解析XML文档

XML 解析---dom解析和sax解析

笔记:XML-解析文档-DOM