无限地吸取知识

快乐就是一生中最大的享受!

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  3 Posts :: 0 Stories :: 2 Comments :: 0 Trackbacks
使用DOM解析XML文件是Java程序员必备的知识,适用于小型的文件解析。
DOM最大的特点是整个文件必须在内存中解析和存储,对于那些需要对文档不同部分进行重复、随机访问的应用程序。

<?xml version="1.0" encoding="UTF-8"?>
<persons>
    
<person no="1">
        
<name>张三</name>
        
<age>21</age>
        
<sex></sex>
    
</person>
    
<person no="2">
        
<name>小红</name>
        
<age>18</age>
        
<sex></sex>
    
</person>
    
<person no="3">
        
<name>陈刚</name>
        
<age>25</age>
        
<sex></sex>
    
</person>
</persons>



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

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class DomParse
{
    
public static void main(String[] args)
    {
        
try
        {
            
new DomParse();
        }
        
catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    
public DomParse() throws Exception
    {
        DocumentBuilderFactory dbf 
= DocumentBuilderFactory.newInstance();
        DocumentBuilder db 
= dbf.newDocumentBuilder();
        String path 
= "bin/person.xml";
        Document doc 
= db.parse(path);
        xmlParse(doc);
    }

    
/* XML解析方法 */
    
public void xmlParse(Document doc)
    {
        Node root 
= doc.getDocumentElement(); // 获得根节点

        NodeList childs 
= root.getChildNodes();
        
for (int i = 0; i < childs.getLength(); i++)
        {
            
/* 输出节点属性 */
            Node childNode 
= childs.item(i);
            
if (childNode.getNodeType() == Node.ELEMENT_NODE)// 判断是否为元素节点
                System.out.println(childNode.getNodeName()
                        
+ childNode.getAttributes().item(0).getNodeValue());

            
/* 输出节点值 */
            
for (int j = 0; j < childNode.getChildNodes().getLength(); j++)
            {
                Node child 
= childNode.getChildNodes().item(j);
                
if (child.getNodeType() == Node.ELEMENT_NODE)
                    System.out.println(child.getNodeName() 
+ "="
                            
+ child.getFirstChild().getNodeValue());
            }
        }
    }
}
posted on 2007-09-16 18:07 Sylar 阅读(634) 评论(0)  编辑  收藏 所属分类: Java基础类

只有注册用户登录后才能发表评论。


网站导航: