---
title: "各位大虾帮小弟解释下这段代码"
author: "6234837"
date: "2009-08-26T15:49:26Z"
tags: []
slug: "untitled"
draft: false
lastmod: "2009-08-26T15:52:06Z"
id: 458013
url: "https://6234837.iteye.com/blog/458013"
---

import java.io.File;
import java.io.*;
import org.w3c.dom.Document;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public  class test
{
	public test()
	{
		try
        {
                    DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
                 DocumentBuilder db=dbf.newDocumentBuilder();
	        File file=new File("test.xml");
                 Document doc=db.parse(file);
	        NodeList products=doc.getElementsByTagName("product");
	        Element productElement;
	        for (int i = 0; i < products.getLength(); i++)
	        {
	            productElement=(Element)products.item(i);
	            String id=productElement.getAttribute("id");
	            System.out.println("产品编号: "+id);
	            String name=doc.getElementsByTagName("name").item(i).getFirstChild().getNodeValue();
	            System.out.println("产品名称: "+name); 
	            String price=doc.getElementsByTagName("price").item(i).getFirstChild().getNodeValue();
	            System.out.println("产品价格: "+price);
	            System.out.println("--------------------------------------"); 
	        }       
         }
        catch(Exception e)
        {
            e.printStackTrace();
        }
	}
	public static void main(String args)
	{
		new test();
	}
}



这段代码是我在网上找的 ，我们老师教我们用java去读取xml  但是我还是不动这段代码