<breakfast_menu>
<food>
<name>Belgian Waffles</name>
<price>$5.95</price>
<description>
Two of our famous Belgian Waffles with plenty of real maple syrup
</description>
<calories>650</calories>
</food>
<food>
<name>Strawberry Belgian Waffles</name>
<price>$7.95</price>
<description>
Light Belgian waffles covered with strawberries and whipped cream
</description>
<calories>900</calories>
</food>
<food>
<name>Berry-Berry Belgian Waffles</name>
<price>$8.95</price>
<description>
Light Belgian waffles covered with an assortment of fresh berries and whipped cream
</description>
<calories>900</calories>
</food>
<food>
<name>French Toast</name>
<price>$4.50</price>
<description>
Thick slices made from our homemade sourdough bread
</description>
<calories>600</calories>
</food>
</breakfast_menu>
I am getting stucked while sorting the xml alphabetically and convert it into the JSON array. The breakfast_menu needs to be sorted by name
If you are using Java 8 , you should check out my open source library: unXml . unXml basically maps from Xpaths to Json-attributes.
It's available on Maven Central .
Example
import java.util.stream.StreamSupport;
import java.util.stream.Collectors;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.nerdforge.unxml.factory.ParsingFactory;
import com.nerdforge.unxml.parsers.Parser;
import org.w3c.dom.Document;
public class Parser {
public List<JsonNode> parseXml(String xml){
Document document = parsing.xml().document(xml);
// parsing xml to Json
Parser<ArrayNode> parser = parsing.arr("/breakfast_menu/food")
.attribute("name")
.attribute("price")
.attribute("description")
.attribute("calories")
.build();
ArrayNode jsonArray = parser.apply(document);
// sorting
List<JsonNode> result = StreamSupport.stream(jsonArray.spliterator(), false)
.sorted((first, second) -> first.get("name").asText().compareTo(second.get("name").asText()))
.collect(Collectors.toList());
return result;
}
}
It will return a List of Jackson JsonNode
.
[{
"price" : "$5.95",
"name" : "Belgian Waffles",
"description" : " Two of our famous Belgian Waffles with plenty of real maple syrup ",
"calories" : "650"
},
{
"price" : "$8.95",
"name" : "Berry-Berry Belgian Waffles",
"description" : " Light Belgian waffles covered with an assortment of fresh berries and whipped cream ",
"calories" : "900"
},
{
"price" : "$4.50",
"name" : "French Toast",
"description" : " Thick slices made from our homemade sourdough bread ",
"calories" : "600"
},
{
"price" : "$7.95",
"name" : "Strawberry Belgian Waffles",
"description" : " Light Belgian waffles covered with strawberries and whipped cream ",
"calories" : "900"
}]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.