要操作的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());
}
}
}