- Home
- Forum
- Angular - EJ 2
- Treeview with dynamic data source
Treeview with dynamic data source
I am trying to create a tree-view in an Angular 7 application with XML data source. I am successfully able to create the example to create a tree-view with static json with ID, name and subchild. I want a user input of both JSON and XML where I will not have the id, namee or subchild. Is there a way or example to populate this treeview dynamically?
SIGN IN To post a reply.
6 Replies
CI
Christopher Issac Sunder K
Syncfusion Team
July 18, 2019 01:04 PM UTC
Hi Shaurya,
Greetings from Syncfusion support.
We have prepared a sample for dynamically bind the XML datasource to the treeview. We used a generic method to convert the unknown structure of XML data to JSON with the required format for TreeView.
In the below example, we have bound the raw XML data into our EJ2 TreeView by using a generic method (convertTreeData). This method is used to convert raw XML data to required JSON of TreeView by provided the mapping field.
|
[HTML]
<script>
// pass your raw xml data here
var encodedStr = '<level3Response><messages><messagetext="Syncfusion"><correlationId>01710231451275401143</correlationId><messageId>20171023145-1275401143</messageId><responseTime>15ms</responseTime></message></messages></level3Response>';
//define the mapper field to be displayed as text in TreeView
var mapper = [];
//it will replace the tag name to custom attribute as TreeView node text
mapper.push({ TagName: "message", TextField: "text" });
convertTreeData(encodedStr, mapper);
//to convert raw xml to xml text node
function convertTreeData(encodedStr, mapper) {
window.treeData = [];
window.id = 1;
var parser = new DOMParser;
var dom = parser.parseFromString(
'<!doctype html><body>' + encodedStr,
'text/html');
var decodedString = dom.body.textContent;
var XmlData = parser.parseFromString(decodedString, "text/xml");
xmlToJson(XmlData, window.treeData, mapper);
}
//to convert xml to json with required format
function xmlToJson(args, treeData, mapper) {
for (var i = 0, length = args.childNodes.length; i < length; i++) {
var nodeText = undefined, tag = args.childNodes[i]
for (var j = 0; j < mapper.length; j++) {
if (mapper[j].TagName == tag.tagName) {
nodeText = tag.getAttribute(mapper[j].TextField);
break;
}
}
nodeText = (nodeText != undefined) ? nodeText : (tag.nodeType == 1 ? tag.tagName : tag.textContent);
var obj = { "NodeId": window.id, "NodeText": nodeText };
treeData.push(obj);
window.id++;
if (args.hasChildNodes()) {
if (obj['Nodechild'] == undefined) {
obj['Nodechild'] = [];
}
xmlToJson(tag, obj['Nodechild'], mapper);
if (obj["Nodechild"].length == 0) {
delete obj["Nodechild"];
}
}
}
}
</script> |
Sample:
Please check the sample and let us know if you have any concerns on this.
Thanks,
Christo
Christo
Hi Shaurya,
Greetings from Syncfusion support.
We have prepared a sample for dynamically bind the XML datasource to the treeview. We used a generic method to convert the unknown structure of XML data to JSON with the required format for TreeView.In the below example, we have bound the raw XML data into our EJ2 TreeView by using a generic method (convertTreeData). This method is used to convert raw XML data to required JSON of TreeView by provided the mapping field.
[HTML]
<script>// pass your raw xml data herevar encodedStr = '<level3Response><messages><messagetext="Syncfusion"><correlationId>01710231451275401143</correlationId><messageId>20171023145-1275401143</messageId><responseTime>15ms</responseTime></message></messages></level3Response>';//define the mapper field to be displayed as text in TreeViewvar mapper = [];//it will replace the tag name to custom attribute as TreeView node textmapper.push({ TagName: "message", TextField: "text" });convertTreeData(encodedStr, mapper);//to convert raw xml to xml text nodefunction convertTreeData(encodedStr, mapper) {window.treeData = [];window.id = 1;var parser = new DOMParser;var dom = parser.parseFromString('<!doctype html><body>' + encodedStr,'text/html');var decodedString = dom.body.textContent;var XmlData = parser.parseFromString(decodedString, "text/xml");xmlToJson(XmlData, window.treeData, mapper);}//to convert xml to json with required formatfunction xmlToJson(args, treeData, mapper) {for (var i = 0, length = args.childNodes.length; i < length; i++) {var nodeText = undefined, tag = args.childNodes[i]for (var j = 0; j < mapper.length; j++) {if (mapper[j].TagName == tag.tagName) {nodeText = tag.getAttribute(mapper[j].TextField);break;}}nodeText = (nodeText != undefined) ? nodeText : (tag.nodeType == 1 ? tag.tagName : tag.textContent);var obj = { "NodeId": window.id, "NodeText": nodeText };treeData.push(obj);window.id++;if (args.hasChildNodes()) {if (obj['Nodechild'] == undefined) {obj['Nodechild'] = [];}xmlToJson(tag, obj['Nodechild'], mapper);if (obj["Nodechild"].length == 0) {delete obj["Nodechild"];}}}}</script>
Sample:
Please check the sample and let us know if you have any concerns on this.
Thanks,
Christo
Hi Chris,
Thanks for your response. I was able to use the given example and create a basic treeview out of a basic xml. For example, the xml I used for which I could create a treeview was the following-
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
This successfully gets converted into treeview-
But when throwing a bigger XML at this, it breaks and gives a parsing error. I have taken time to fix it but I am still stuck and hence me reaching out to you again.
<?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>
<book id="bk103">
<author>Corets, Eva</author>
<title>Maeve Ascendant</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-11-17</publish_date>
<description>After the collapse of a nanotechnology
society in England, the young survivors lay the
foundation for a new society.</description>
</book>
<book id="bk104">
<author>Corets, Eva</author>
<title>Oberon's Legacy</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2001-03-10</publish_date>
<description>In post-apocalypse England, the mysterious
agent known only as Oberon helps to create a new life
for the inhabitants of London. Sequel to Maeve
Ascendant.</description>
</book>
<book id="bk105">
<author>Corets, Eva</author>
<title>The Sundered Grail</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2001-09-10</publish_date>
<description>The two daughters of Maeve, half-sisters,
battle one another for control of England. Sequel to
Oberon's Legacy.</description>
</book>
<book id="bk106">
<author>Randall, Cynthia</author>
<title>Lover Birds</title>
<genre>Romance</genre>
<price>4.95</price>
<publish_date>2000-09-02</publish_date>
<description>When Carla meets Paul at an ornithology
conference, tempers fly as feathers get ruffled.</description>
</book>
<book id="bk107">
<author>Thurman, Paula</author>
<title>Splish Splash</title>
<genre>Romance</genre>
<price>4.95</price>
<publish_date>2000-11-02</publish_date>
<description>A deep sea diver finds true love twenty
thousand leagues beneath the sea.</description>
</book>
<book id="bk108">
<author>Knorr, Stefan</author>
<title>Creepy Crawlies</title>
<genre>Horror</genre>
<price>4.95</price>
<publish_date>2000-12-06</publish_date>
<description>An anthology of horror stories about roaches,
centipedes, scorpions and other insects.</description>
</book>
<book id="bk109">
<author>Kress, Peter</author>
<title>Paradox Lost</title>
<genre>Science Fiction</genre>
<price>6.95</price>
<publish_date>2000-11-02</publish_date>
<description>After an inadvertant trip through a Heisenberg
Uncertainty Device, James Salway discovers the problems
of being quantum.</description>
</book>
<book id="bk110">
<author>O'Brien, Tim</author>
<title>Microsoft .NET: The Programming Bible</title>
<genre>Computer</genre>
<price>36.95</price>
<publish_date>2000-12-09</publish_date>
<description>Microsoft's .NET initiative is explored in
detail in this deep programmer's reference.</description>
</book>
<book id="bk111">
<author>O'Brien, Tim</author>
<title>MSXML3: A Comprehensive Guide</title>
<genre>Computer</genre>
<price>36.95</price>
<publish_date>2000-12-01</publish_date>
<description>The Microsoft MSXML3 parser is covered in
detail, with attention to XML DOM interfaces, XSLT processing,
SAX and more.</description>
</book>
<book id="bk112">
<author>Galos, Mike</author>
<title>Visual Studio 7: A Comprehensive Guide</title>
<genre>Computer</genre>
<price>49.95</price>
<publish_date>2001-04-16</publish_date>
<description>Microsoft Visual Studio 7 is explored in depth,
looking at how Visual Basic, Visual C++, C#, and ASP+ are
integrated into a comprehensive development
environment.</description>
</book>
</catalog>
<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>
<book id="bk103">
<author>Corets, Eva</author>
<title>Maeve Ascendant</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-11-17</publish_date>
<description>After the collapse of a nanotechnology
society in England, the young survivors lay the
foundation for a new society.</description>
</book>
<book id="bk104">
<author>Corets, Eva</author>
<title>Oberon's Legacy</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2001-03-10</publish_date>
<description>In post-apocalypse England, the mysterious
agent known only as Oberon helps to create a new life
for the inhabitants of London. Sequel to Maeve
Ascendant.</description>
</book>
<book id="bk105">
<author>Corets, Eva</author>
<title>The Sundered Grail</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2001-09-10</publish_date>
<description>The two daughters of Maeve, half-sisters,
battle one another for control of England. Sequel to
Oberon's Legacy.</description>
</book>
<book id="bk106">
<author>Randall, Cynthia</author>
<title>Lover Birds</title>
<genre>Romance</genre>
<price>4.95</price>
<publish_date>2000-09-02</publish_date>
<description>When Carla meets Paul at an ornithology
conference, tempers fly as feathers get ruffled.</description>
</book>
<book id="bk107">
<author>Thurman, Paula</author>
<title>Splish Splash</title>
<genre>Romance</genre>
<price>4.95</price>
<publish_date>2000-11-02</publish_date>
<description>A deep sea diver finds true love twenty
thousand leagues beneath the sea.</description>
</book>
<book id="bk108">
<author>Knorr, Stefan</author>
<title>Creepy Crawlies</title>
<genre>Horror</genre>
<price>4.95</price>
<publish_date>2000-12-06</publish_date>
<description>An anthology of horror stories about roaches,
centipedes, scorpions and other insects.</description>
</book>
<book id="bk109">
<author>Kress, Peter</author>
<title>Paradox Lost</title>
<genre>Science Fiction</genre>
<price>6.95</price>
<publish_date>2000-11-02</publish_date>
<description>After an inadvertant trip through a Heisenberg
Uncertainty Device, James Salway discovers the problems
of being quantum.</description>
</book>
<book id="bk110">
<author>O'Brien, Tim</author>
<title>Microsoft .NET: The Programming Bible</title>
<genre>Computer</genre>
<price>36.95</price>
<publish_date>2000-12-09</publish_date>
<description>Microsoft's .NET initiative is explored in
detail in this deep programmer's reference.</description>
</book>
<book id="bk111">
<author>O'Brien, Tim</author>
<title>MSXML3: A Comprehensive Guide</title>
<genre>Computer</genre>
<price>36.95</price>
<publish_date>2000-12-01</publish_date>
<description>The Microsoft MSXML3 parser is covered in
detail, with attention to XML DOM interfaces, XSLT processing,
SAX and more.</description>
</book>
<book id="bk112">
<author>Galos, Mike</author>
<title>Visual Studio 7: A Comprehensive Guide</title>
<genre>Computer</genre>
<price>49.95</price>
<publish_date>2001-04-16</publish_date>
<description>Microsoft Visual Studio 7 is explored in depth,
looking at how Visual Basic, Visual C++, C#, and ASP+ are
integrated into a comprehensive development
environment.</description>
</book>
</catalog>
This example breaks and this is the expanded treeview-
--Parsing error--
I have tried other big xmls and they are all breaking in the same manner.
Also, would you be able to provide an example of using a raw json instead of raw xml if its something that is already prepared?
Appreciate all your help here.
Thanks,
Shaurya
SS
Shaurya Singh
July 23, 2019 07:43 PM UTC
What I can also add is that whenever an XML tag has information along with it, that is when it breaks- <test>Something </test> will work but <test id="1"> Something</test> will not work. Can we cater for this ?
Thanks
CI
Christopher Issac Sunder K
Syncfusion Team
July 25, 2019 11:52 AM UTC
Hi Shaurya,
We have prepared a sample based on your shared XML file using the inbuilt XML parser in the angular-CLI application.
Please refer to this: https://www.npmjs.com/package/xml2js
Here we fetched the XML data using ajax request and parse it as JSON using the inbuilt parser. Please find the corresponding code snippet.
|
public onCreate()
{
var proxy = this;
const ajax = new Ajax('http://localhost/xmlData/myFile.xml', 'GET');
ajax.send();
ajax.onSuccess = (data: any) => {
var parseString = require('xml2js').parseString;
parseString(data, function(err, result) {
var dataSource = result.catalog.book;
proxy.tree.fields.dataSource = dataSource;
});
};
} |
Output image:
Parsed-data:
Rendered-tree
Note: Here we hosted the xml file in local and provided that file path in ajax URL
Please check the above sample and let us know if you have any concerns.
Thanks,
Christo
SS
Shaurya Singh
July 26, 2019 06:58 PM UTC
Hey Chris,
hate to say it but the example you sent does not build for me and when compiling it gives me a few core file errors. It is missing some ';' that I cant get into the file and edit.
Thanks
Shaurya
AB
Ashokkumar Balasubramanian
Syncfusion Team
July 29, 2019 10:51 AM UTC
Hi Shaurya,
Sorry for the inconvenience caused.
We have checked the reported issue and it was due to the rxjs version. We have resolved it by upgrading its version. Please find the modified sample from the below link
Kindly check the sample and get back to us if you have any concerns.
Regards,
Ashokkumar B.
SIGN IN To post a reply.
- 6 Replies
- 3 Participants
-
SS Shaurya Singh
- Jul 17, 2019 02:22 PM UTC
- Jul 29, 2019 10:51 AM UTC