ChenGen

一切归零,重新开始
随笔 - 13, 文章 - 10, 评论 - 21, 引用 - 0
数据加载中……

java xml 操作小结

要操作的XML文档
<?xml version="1.0" encoding="UTF-8"?>
<xml>
    
<projectid>testThreading</projectid>
    
<projectype>1</projectype>
    
<tasklist>
        
<task>
            
<name>sub4</name>
            
<exe>FoldRec.exe</exe>
            
<attribute>1</attribute>
        
</task>
        
<task>
            
<name>sub3</name>
            
<exe>FoldRec.exe</exe>
            
<attribute>1</attribute>
        
</task>
        
<task>
            
<name>sub2</name>
            
<exe>FoldRec.exe</exe>
            
<attribute>1</attribute>
        
</task>
        
<task>
            
<name>sub1</name>
            
<exe>FoldRec.exe</exe>
            
<attribute>1</attribute>
        
</task>
    
</tasklist>
</xml>
目的是要读出 tasklist 下面每个 task 的名字:
sub1
sub2
sub3
...

package xml;

import java.io.File;

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

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

public class ProjectParser {
    
public static void main(String args[]) throws Exception{
        DocumentBuilderFactory factory
=DocumentBuilderFactory.newInstance();
        DocumentBuilder builder
=factory.newDocumentBuilder();
        Document doc
=builder.parse(new File("3.xml"));
        NodeList list
=doc.getElementsByTagName("task");
        
for(int i=0;i<list.getLength();i++){
            Element task
=(Element)list.item(i);
            NodeList names
=task.getElementsByTagName("name");
            Element name
=(Element)names.item(0);
            Text text
=(Text)name.getFirstChild();
            System.out.println(text.getNodeValue());
        }
    }
}


posted on 2007-04-11 09:29 ChenGen 阅读(229) 评论(0)  编辑  收藏 所属分类: JAVA基础


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


网站导航: