XML as a data source for the Vaadin tree

a small im project is working, in this project I have to display some data from an XML source / file in the Vaadin tree.

My question is: can I do this with the Vaadin tree and how "hard" is it to implement?

I looked at the Vaadin demo trees, they all use Containers as a source, so I don’t know if it will work with XML.

I am new in XML and Java, so I have not been able to post some useful tutorials / links

+4
source share
1 answer

There are many java libraries for processing xml. Just take, for example, XOM, and convert it to a Hierarchical container.

For example, an example of reading XML here: http://bethecoder.com/applications/tutorials/xml-xom-read-xml.html and converting it to IndexedContainer:

<?xml version="1.0"?> <students> <student> <name>Sriram</name> <age>2</age> </student> <student> <name>Venkat</name> <age>29</age> </student> <student> <name>Anu</name> <age>28</age> </student> </students> 

Now we can change the code and throw the data into the container:

 Builder builder = new Builder(); InputStream ins = ReadXML.class.getClassLoader() .getResourceAsStream("student_list.xml"); //Reads and parses the XML Document doc = builder.build(ins); Element root = doc.getRootElement(); IndexedContainer container = new IndexedContainer(); container.addContainerProperty("name", String.class, null); container.addContainerProperty("age", Integer.class, null); //Get children Elements students = root.getChildElements(); for (int i = 0 ; i < students.size() ; i ++) { System.out.println(" Child : " + students.get(i).getLocalName()); Object student = container.addItem(); Item studentItem = container.getItem(student); //Get first child with tag name as 'name' Element nameChild = students.get(i).getFirstChildElement("name"); if (nameChild != null) { studentItem.getItemProperty("name").setValue(nameChild.getValue()); } Element ageChild = students.get(i).getFirstChildElement("age"); if (ageChild != null) { studentItem.getItemProperty("age").setValue(ageChild.getValue()); } } 

Now that the indexed container can be connected to a table or tree. You can change it to a HierarchicalContainer if you have the tree format in xml and use setParent in the container. If you want to show several properties, you should go with TreeTable instead of Tree, since Tree shows only one property.

+8
source

Source: https://habr.com/ru/post/1380722/


All Articles