Java读取xml


  1. import java.io.*;   
  2. import org.w3c.dom.*;   
  3. import org.xml.sax.SAXException;   
  4. import javax.xml.parsers.*;   
  5. public class Xml {   
  6.     public static void main(String[] args) {   
  7.         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();   
  8.         try {   
  9.             DocumentBuilder builder = factory.newDocumentBuilder();   
  10.             Document doc = builder.parse(new File("E:\\work\\test\\xml1.xml"));   
  11.             NodeList nl = doc.getElementsByTagName("book");   
  12.             for (int i = 0; i < nl.getLength(); i++) {   
  13.                 System.out.println(nl.item(i).getAttributes().item(0));   
  14.                 System.out.println(doc.getElementsByTagName("title").item(i)   
  15.                         .getFirstChild().getNodeValue());   
  16.                 System.out.println(doc.getElementsByTagName("title").item(i)   
  17.                         .getAttributes().item(0));   
  18.                 System.out.println(doc.getElementsByTagName("author").item(i)   
  19.                         .getFirstChild().getNodeValue());   
  20.                 System.out.println(doc.getElementsByTagName("year").item(i)   
  21.                         .getFirstChild().getNodeValue());   
  22.                 System.out.println(doc.getElementsByTagName("price").item(i)   
  23.                         .getFirstChild().getNodeValue());   
  24.                 System.out.println();   
  25.             }   
  26.         } catch (ParserConfigurationException e) {   
  27.             e.printStackTrace();   
  28.         } catch (SAXException e) {   
  29.             e.printStackTrace();   
  30.         } catch (IOException e) {   
  31.             e.printStackTrace();   
  32.         }   
  33.     }   
  34. }   

 xml:

  1. <bookstore>  
  2. <book category="COOKING">  
  3.   <title lang="en">Everyday Italian</title>  
  4.   <author>Giada De Laurentiis</author>  
  5.   <year>2005</year>  
  6.   <price>30.00</price>  
  7. </book>  
  8. <book category="CHILDREN">  
  9.   <title lang="en">Harry Potter</title>  
  10.   <author>J K. Rowling</author>  
  11.   <year>2005</year>  
  12.   <price>29.99</price>  
  13. </book>  
  14. <book category="WEB">  
  15.   <title lang="en">Learning XML</title>  
  16.   <author>Erik T. Ray</author>  
  17.   <year>2003</year>  
  18.   <price>39.95</price>  
  19. </book>  
  20. </bookstore>  

Result:

category="COOKING"
Everyday Italian
lang="en"
Giada De Laurentiis
2005
30.00

category="CHILDREN"
Harry Potter
lang="en"
J K. Rowling
2005
29.99

category="WEB"
Learning XML
lang="en"
Erik T. Ray
2003
39.95

相关内容