Home > Blockchain >  How to extract xml data to a list of Map of Strings?
How to extract xml data to a list of Map of Strings?

Time:01-28

I have an xml data like this

  `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
   <books>
     <book>
       <name>SCJP</name>
       <author>Kathy Sierra</author>
       <publisher>Tata McGraw Hill</publisher>
       <isbn>856-545456736</isbn>
     </book>
     <book>
       <name>Java Persistence with Hibernate</name>
       <author>Christian Bauer</author>
       <publisher>Manning</publisher>
       <isbn>978-3832180577</isbn>
     </book>
   </books>`

Is there a way to to convert this xml data to List<Map<String,String>> or List<Map<String,Object>> with out using a class? .Please help. Thanks

I have tried to extract this with java code using JAX unmarshalling ,

https://ibytecode.com/blog/jaxb-marshalling-and-unmarshalling-list-of-objects/,

which is working for me and i am getting results like

  [Book [name=SCJP, author=Kathy Sierra, publisher=Tata McGraw Hill, isbn=856-545456736], 
  Book [name=Java Persistence with Hibernate, author=Christian Bauer, publisher=Manning, isbn=978-  3832180577]]

I am only expecting

[{name="SCJP", author="Kathy Sierra", publisher="Tata McGraw Hill", isbn="856-545456736"}, {name="Java Persistence with Hibernate", author="Christian Bauer", publisher="Manning", isbn="978- 3832180577"}]

CodePudding user response:

In XQuery 3.1, using the Saxon API, run the query

/books/book ! map:merge(* ! map{local-name(.) : string(.)})

This will return an XdmValue which can be processed directly in your Java application, or converted to the form you require. To convert it to a List<Map<String, String>> you could use

List<Map<String, String> list = new ArrayList<>();
for (XdmItem item : xdmValue) {
  XdmMap xMap = (XdmMap)item;
  Map<String, String> jMap = new HashMap<>();
  for (XdmAtomicValue key : xMap.keySet()) {
     jMap.put(key.getStringValue(),
              ((XdmAtomicValue)xMap.get(key)).getStringValue();
  }
  list.add(jMap);
}

In my view this kind of approach is much more flexible than anything using JAXB, because your application does not have any tight coupling to the XML schema for the data.

You could of course use a different XQuery 3.1 processor such as BaseX, but the API would be slightly different.

  • Related