34

How to display a XML document in a HTML page as a collapsible and expandable tree?

I'd like to display a XML document inside a HTML page as a nicely pretty printed tree structure. I'd like to be able to expand and collapse tree branches. For example Firefox browser does this when you load a plain XML file. I am looking how to do this in client-side with JavaScript.

Juha Syrjälä
  • 33,425
  • 31
  • 131
  • 183

5 Answers5

18

Creating An XML Viewer With JScript - Exsead XML Power Scripting

Display XML Files with Javascript

Update:

There seems to be a better and easier-to-use alternative than what I listed above many years ago:

https://www.jstree.com/

Hope they help.

Tarik
  • 79,711
  • 83
  • 236
  • 349
  • Confused about JStree Update. The XML format required for JSTree it is very specific. Wouldn't you need to transform it from one xml format to another? – Simon Sep 13 '18 at 17:16
1

This library does all the work for you:

http://www.openjsan.org/doc/k/ka/kawasaki/XML/ObjTree/0.24/lib/XML/ObjTree.html

var js = (new XML.ObjTree).parse("<?xml version="1.0"?><response><error>0</error></response>");

Then you have a JavaScript tree and you can display it however you want. You might want to try the YAHOO.widget.TreeView module for that it will create a "expandable and collapsible tree." That is if you like the YUI library, other wise there is Dojo and Ext libraries that can create a treeview for you.

jhuni
  • 425
  • 3
  • 4
0

Hi just add this to the header of your page.

<?php

header("Content-type: text/xml");

$xml = new SimpleXMLElement('<xml/>');

for ($i = 1; $i <= 8; ++$i) {
    $track = $xml->addChild('track');
    $track->addChild('path', "song$i.mp3");
    $track->addChild('title', "Track $i - Track Title");
}

print($xml->asXML());
?>
Louwki
  • 696
  • 1
  • 9
  • 21
0

http://ajaxian.com/archives/jstree-jquery-based-javascript-tree-component Here you can find a bunch of js libs with solutions

Eldar Djafarov
  • 23,327
  • 2
  • 33
  • 27
0

If you are using ASP.NET application then there is no need for client side functionality. You can use the below specified method:-

//Populate the below varaible value from your business logic
string xmlContent = "<?xml version=\"1.0\"><root><emp><name>name 1</name></emp><emp><name>name 2</name></emp></root>";
Response.Clear();
Response.ContentType = "text/xml"; //Set the contenttype to text/xml so the browser automatically recognises and displays it in the hierarchical structure
Response.Write(xmlContent);
Response.Flush();
Response.End();
Juha Syrjälä
  • 33,425
  • 31
  • 131
  • 183
  • 5
    That will cause server response to be whole XML document. I was looking for solution where a part of HTML page is a pritty printed XML. And a client side/Javascript based solution. – Juha Syrjälä Jan 05 '11 at 08:11