import javax.xml.parsers.*; |
import org.w3c.dom.*; |
import org.xml.sax.SAXException; |
import java.io.File; |
import java.io.IOException; |
//解析xml文件(jaxp) |
public class XMLReader{ |
public static void main(String[] args){ //为简单起见直接写到main里面 |
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); |
//建立解析工厂对象 |
try { |
DocumentBuilder db=dbf.newDocumentBuilder(); //创建解析者 |
File file= new File( "test.xml" ); |
Document doc=db.parse(file); //解析xml文件 |
NodeList nl=doc.getElementsByTagName( "customer" ); |
int len=nl.getLength(); //取得nodelist的长度 |
for ( int i= 0 ;i<len;i++){ |
Element customer=(Element)nl.item(i); |
Node id=customer.getElementsByTagName( "id" ).item( 0 ); |
Node name=customer.getElementsByTagName( "name" ).item( 0 ); |
String newid=id.getFirstChild().getNodeValue(); |
String newname=name.getFirstChild().getNodeValue(); |
System.out.print( "id号:" ); |
System.out.println(newid); |
System.out.print( "名字:" ); |
System.out.println(newname); |
} |
} catch (Exception e) { //避免复杂,详细例外省略} |
} |
} |