Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML as a data source for a Vaadin tree

there is a small project im working on , in this project i have to display some data from an XML Source / file in a Vaadin tree.

My question is : can i do it with Vaadin tree and how "hard" would it be to realize it ?

i have looked at the Vaadin demo trees they are all using Containers as a source so dont know if it would work with XML.

Im new in XML and Java so fell free to post some usefull guides/links

like image 980
Kiesa Avatar asked Feb 22 '23 10:02

Kiesa


1 Answers

There are proablably a lot of java libraries out there for processing xml. Just take one, like XOM for example, and convert it to a HierarchicalContainer.

For example, taking the XML reading example found here: http://bethecoder.com/applications/tutorials/xml-xom-read-xml.html and converting it to an 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>

We can now modify the code there and throw the data into a 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 indexedcontainer can be plugged into a table or tree. You can change it to a HierarchicalContainer if you have a tree format in your xml, and use setParent on the container. If you want to show multiple properties you'd have to go with the TreeTable instead of Tree, as Tree only shows one property.

like image 55
Jens Jansson Avatar answered Feb 24 '23 23:02

Jens Jansson