How to display XML in a HTML page as a collapsible

2019-01-17 06:10发布

问题:

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.

回答1:

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.



回答2:

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



回答3:

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.



回答4:

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();


回答5:

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());
?>