使用Java问题解析XML文件

时间:2017-04-03 16:39:29

标签: xml

我试图获取此XML文件

<CATALOG>
<CD>
<TITLE>Empire Burlesque</TITLE>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
<CD>
<TITLE>Hide your heart</TITLE>
<ARTIST>Bonnie Tyler</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>CBS Records</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1988</YEAR>
</CD>
<CD>
<TITLE>Unchain my heart</TITLE>
<ARTIST>Joe Cocker</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>EMI</COMPANY>
<PRICE>8.20</PRICE>
<YEAR>1987</YEAR>
</CD>
</CATALOG>

用此输出解析

parsing cd_catalog.xml
Document root node is: CATALOG
 First CD Data:
Empire Burlesque
Bob Dylan
USA
Columbia
10.90
1985
 Second CD Data:
Hide your heart
Bonnie Tyler
UK
CBS Records
9.90
1988
 Last CD Data:
Unchain my heart
Joe Cocker
USA
EMI
8.20
1987
Total Number of CDs is: 26

我在下面有这个代码进行解析,但它输出&#34; First CD Data&#34;对于每张CD,我都需要去'第一张CD数据&#34; &#34;第二张CD数据&#34;和&#34;最后的CD数据&#34;。

    private static void printNodes() {


      Element root = document.getDocumentElement();
      System.out.println(root.getNodeName());

      //Get all CDS
      NodeList nList = document.getElementsByTagName("CD");
      System.out.println("============================");

      for (int temp = 0; temp < 2; temp++)
      {
       Node node = nList.item(temp);
       System.out.println("");   
       if (node.getNodeType() == Node.ELEMENT_NODE)
       {
          //Print each CD's details
          Element eElement = (Element) node;
          System.out.println("First CD data is : "    + eElement.getAttribute("TITLE"));
          System.out.println(eElement.getElementsByTagName("ARTIST").item(0).getTextContent());
          System.out.println(eElement.getElementsByTagName("COUNTRY").item(0).getTextContent());
          System.out.println(eElement.getElementsByTagName("COMPANY").item(0).getTextContent());
          System.out.println(eElement.getElementsByTagName("PRICE").item(0).getTextContent());
          System.out.println(eElement.getElementsByTagName("YEAR").item(0).getTextContent());



       }
      }

  }

我的计划是采用for循环,我已经减少到1,所以它打印掉所有第一张CD的数据,然后为下一张CD制作另一个循环,但我不确定如何查找数组列表中的CD,然后我将为最后一张CD做什么。

1 个答案:

答案 0 :(得分:0)

非常简单, 将XML转换为JAXB类 使用在线转换器:http://pojo.sodhanalibrary.com/

尝试{

    File file = new File("cd_catalog.xml");  
    JAXBContext jaxbContext = JAXBContext.newInstance(Catalog.class);  

    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();  
    Catalog cat= (Catalog) jaxbUnmarshaller.unmarshal(file);  

    List<CD> list=cat.getCD();  
    for(CD cd:list)  
      System.out.println(cd.getArtist());  

  } catch (JAXBException e) {  
    e.printStackTrace();  
  }