I have an interesting problem. I want to process an XML file into individual JSON objects (JSONObject). But in a functional way.
I have a source XMLfile that contains Property Groups. Each group containing properties (see below).
The only way to tell if a group belongs to different products is by the id
attribute.
<data>
<products>
<property_group classification="product_properties" id="1234">
<property name="Name">Product1</property>
<property name="Brand">Brand1</property>
...
</property_group>
<property_group classification="size_properties" id="1234">
<property name="width">200cm</property>
<property name="height">100cm</property>
...
</property_group>
...
<property_group classification="product_properties" id="5678">
<property name="Name">Product2</property>
<property name="Brand">Brand2</property>
...
</property_group>
<property_group classification="weight_properties" id="5678">
<property name="kg">20</property>
<property name="lbs">44</property>
...
</property_group>
...
</products>
</data>
My code for processing this XML file looks like this:
def createProducts(propertyGroups: NodeSeq): MutableList[JSONObject] = {
val products = new MutableList[JSONObject]
var productJSON = new JSONObject()
var currentProductID = "";
propertyGroups.foreach { propertyGroup => {
// Get data from the current property_group
val productID = getProductID(propertyGroup)
val propertiesClassification = getClassification(propertyGroup)
val properties = getProductAttributes(propertyGroup \\ "property")
// Does this group relates to a new product?
if(currentProductID != productID){
// Starting a new Product
productJSON = new JSONObject()
products += productJSON
productJSON.put("product", productID)
currentProductID = productID
}
// Add the properties to the product
val propertiesJSON = new JSONObject()
propertiesJSON.put(propertiesClassification, properties)
productJSON.put(propertiesClassification, properties)
} }
return products
}
Although this works and does what it is supposed to do, it is not 'functional style'. How do I change this from the imperative mind-set to a functional style?