循环xml并持久化到数据库java

时间:2015-11-24 15:29:43

标签: java xml rest parsing

我正在尝试循环遍历xml并提取值并使用rest将其持久保存到mysql。这是我到目前为止。但它只提取第一个有值songIts的字符串添加到数据库但id喜欢一次添加两个。

    NodeList artistList = (NodeList)xPath.evaluate("/plist/dict/dict/dict/string[@rollno='artist']", root, XPathConstants.NODESET);
        for (int i = 0; i < artistList.getLength(); ++i) {
            Element e = (Element) artistList.item(i);
            artist= e.getFirstChild().getNodeValue();


            book.setIsbn(artist);
            book.setName(song);



            returnCode = "200";
            em = Resource.getEntityManager();
        }

这是我尝试使用xpath解析的xml我想提取所有rollno =“song”并一个接一个地保留它们,任何建议或帮助都意味着很多。谢谢

  <plist version="1.0">
   <dict>
      <key>Major Version</key>
      <integer>1</integer>
      <key>Application Version</key>
      <string>7.0.2</string>
      <key>Show Content Ratings</key>
      <true />
      <key>Tracks</key>
      <dict>
         <key>1288</key>
         <dict >
            <key>Track ID</key>
            <integer>1288</integer>
            <key>Name</key>
            <string rollno="song">Brighter Than Sush</string>
            <key>Artist</key>
            <string rollno="artist">Aqualug</string>
            <key>Album Artist</key>
            <string>Aqualung</string>
            <key>Album</key>
            <key>Track ID</key>
            <integer>1288</integer>
            <key>Name</key>
            <string rollno="song">james</string>
            <key>Artist</key>
            <string rollno="artist">martha</string>
            <key>Album Artist</key>
            <string>Aqualung</string>
            <key>Album</key>
         </dict>


      </dict>
   </dict>
</plist> 

1 个答案:

答案 0 :(得分:1)

您的XPath / NodeList代码是正确的。因为你只获得了最后一个XML值, 要么在 for循环之后做事(不太可能),要么在循环之前覆盖创建的同一对象的字段。

    for (int i = 0; i < artistList.getLength(); ++i) {
        Element e = (Element) artistList.item(i);
        artist= e.getFirstChild().getNodeValue();

        book = new Book(); // A new object here
        book.setIsbn(artist);
        book.setName(song);
        ... // Process book
    }

为了获得良好的订单,您可能更愿意使用e.getTextContent()