#Angular Material treeview with xml data

4 messages · Page 1 of 1 (latest)

alpine willow
#

I want to display a XML file as treeview with angular material treeview
have this kind of xml structure

<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications 
      with XML.</description>
   </book>
   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>A former architect battles corporate zombies, 
      an evil sorceress, and her own childhood to become queen 
      of the world.</description>
   </book>
   

I use xml2js package to convert the xml to javascript object
Bild
I have a problem to load this now as datasource into the treeview as dynamic data
from the example of the angular material treeview homepage they use a Map<string, string[]>
I am getting the xml data as js object as observable
how can I convert it to a Map so I can use it as dataSource for the treeview

ngOnInit(): void {
    try {
      this.books$ = this.getXmlData('./assets/books.xml');
      this.books$.subscribe((data) => {
        console.log(data);
        // this.dataSource.data = data;
      })
    } catch (err) {
      console.error(err);
      }
  }

  getXmlData(xmlUrl: string): Observable<any> {
    return this.http.get(xmlUrl, { responseType: 'text' })
      .pipe(
        switchMap(async (xml) => await this.parseXmlToJson(xml)));
  }

  async parseXmlToJson(xml:string) {
    // Without parser
    return await xml2js
      .parseStringPromise(xml, { explicitArray: false })
      .then((response: any) => {
        this.books = response;
        return response;
      });
  }
ionic panther
#

Look at the "Tree with nested nodes" example instead, as it matches much more closely with what you want to achieve.

alpine willow
ionic panther
#

You know the struccture: an XML document consists of a root element containing other elements, containing other elements, etc. Each element has a name (catalog, book, author, etc.).