samedi 9 mai 2015

Extract specific elements from an input file and write them to an output file using StAX

Let say that I have the next XML:

<?xml version="1.0" encoding="UTF-8"?>
<orders>
     <order created='2002-02-12T11:10:30.000' ID='1233'>
          <fruit>
               <description>Red apples</description>
               <price currency="USD">13.25</price>
               <gardener>John</gardener>
          <fruit>
          <fruit>
               <description>Bananas</description>
               <price currency="USD">11.19</price>
               <gardener>Ana</gardener>
          <fruit>
          <fruit>
               <description>Golden apples</description>
               <price currency="USD">16.46</price>
               <gardener>John</gardener>
          <fruit>
     </order>
     <order created='2002-02-13T15:32:30.000' ID='1234'>
          <fruit>
               <description>Oranges</description>
               <price currency="USD">10.99</price>
               <gardener>Ana</gardener>
          <fruit>
          <fruit>
               <description>Kiwi</description>
               <price currency="USD">10.39</price>
               <gardener>Helen</gardener>
          <fruit>
     </order>
</orders>

And I need to write one XML file for each distinct gradener. (John, Ana, Helen). The name of the xml file should be like gradener_name## where ## are first 2 digits from the value of ID attribute in "order" element (ex. Ana12). Ex. Ana12.xml

<?xml version="1.0" encoding="UTF-8"?>
<fruits>
     <fruit>
          <description>Bananas</description>
          <price currency="USD">11.19</price>
          <gardener>Ana</gardener>
     <fruit>
     <fruit>
          <description>Oranges</description>
          <price currency="USD">10.99</price>
          <gardener>Ana</gardener>
     <fruit>
</fruits>

Here, the fruits are sorted by price. First fruit is the one with higher price.

Aucun commentaire:

Enregistrer un commentaire