使用JavaScript循环遍历XML节点并输出HTML表

时间:2018-04-27 02:09:51

标签: javascript xml

我正在使用JavaScript创建一个网页来创建一个表,该表对于XML文件中的每个节点都有一个单独的行(注意:我无法使用XSL / XSLT修改XML文件原因)。

    <script>
        if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        var xmlhttp = new XMLHttpRequest();
        } else {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.open("GET", "Books.xml", false);
        xmlhttp.send();
        xmlDoc = xmlhttp.responseXML;
    document.write("<table id=name border='1'>");
    document.write("<tr><th>Book Name</th><th>Book Price</th><th>Book Author</th><th>Book Comments</th></tr>");  document.write("<tr>");

我的问题是XML文件有一组不同的childNodes,具体取决于任何特定书籍的可用内容,例如 -

    <Book>
    <BookName>Cooking Today</BookName>
    <BookPrice>$6.99</BookPrice>
    </Book>

    <Book>
    <BookName>How To Make It</BookName>
    <BookPrice>$7.99</BookPrice>
    <BookAuthor>Gary Shaw</BookAuthor>
    <BookComments>OMG, it changed my life</BookComments>
    </Book> 

我创建的表格中包含每个字段所需的所有列名称,但是因为每本书都有不同的childNodes,所以每行中这些值的位置都不匹配到相应的列

当特定字段不可用时,是否有办法让此脚本输入空白/空/空值(例如,在上面的示例中,我想在表格中留一个空格这本书,&#39;今日烹饪&#39;为缺少的领域 - 书作者,书评?)

1 个答案:

答案 0 :(得分:0)

第一步:定义对象范围

如果您知道每个节点,那么您可以定义对象的所有变量,对吧?然后在尝试执行XML阅读器之前执行此操作。我建议:

<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/92/three.js"></script>
<!DOCTYPE html>
<html lang="en">
	<head>
		<title>three.js webgl - equirectangular panorama</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
		<style>
			body {
				background-color: #000000;
				margin: 0px;
				overflow: hidden;
			}
			#info {
				position: absolute;
				top: 0px; width: 100%;
				color: #ffffff;
				padding: 5px;
				font-family:Monospace;
				font-size:13px;
				font-weight: bold;
				text-align:center;
			}
			a {
				color: #ffffff;
			}
		</style>
	</head>
	<body>

		<div id="container"></div>
		<div id="info">
			<a href="http://threejs.org" target="_blank" rel="noopener">three.js webgl</a> - equirectangular panorama demo. photo by <a href="http://www.flickr.com/photos/jonragnarsson/2294472375/" target="_blank" rel="noopener">Jón Ragnarsson</a>.<br />
			drag equirectangular texture into the page.
		</div>

		<script>
			var camera, scene, renderer;
			var isUserInteracting = false,
			onMouseDownMouseX = 0, onMouseDownMouseY = 0,
			lon = 0, onMouseDownLon = 0,
			lat = 0, onMouseDownLat = 0,
			phi = 0, theta = 0;
			init();
			animate();
			function init() {
				var container, mesh;
				container = document.getElementById( 'container' );
				camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 1100 );
				camera.target = new THREE.Vector3( 0, 0, 0 );
				scene = new THREE.Scene();
				var geometry = new THREE.SphereBufferGeometry( 500, 60, 40 );
				// invert the geometry on the x-axis so that all of the faces point inward
				geometry.scale( - 1, 1, 1 );
				var material = new THREE.MeshBasicMaterial( {
					map: new THREE.TextureLoader().load( 'https://farm4.staticflickr.com/3289/2294472375_24a3b8ef46_o.jpg' )
				} );
				mesh = new THREE.Mesh( geometry, material );
				scene.add( mesh );
				renderer = new THREE.WebGLRenderer();
				renderer.setPixelRatio( window.devicePixelRatio );
				renderer.setSize( window.innerWidth, window.innerHeight );
				container.appendChild( renderer.domElement );
				document.addEventListener( 'mousedown', onDocumentMouseDown, false );
				document.addEventListener( 'mousemove', onDocumentMouseMove, false );
				document.addEventListener( 'mouseup', onDocumentMouseUp, false );
				document.addEventListener( 'wheel', onDocumentMouseWheel, false );
				//
				document.addEventListener( 'dragover', function ( event ) {
					event.preventDefault();
					event.dataTransfer.dropEffect = 'copy';
				}, false );
				document.addEventListener( 'dragenter', function ( event ) {
					document.body.style.opacity = 0.5;
				}, false );
				document.addEventListener( 'dragleave', function ( event ) {
					document.body.style.opacity = 1;
				}, false );
				document.addEventListener( 'drop', function ( event ) {
					event.preventDefault();
					var reader = new FileReader();
					reader.addEventListener( 'load', function ( event ) {
						material.map.image.src = event.target.result;
						material.map.needsUpdate = true;
					}, false );
					reader.readAsDataURL( event.dataTransfer.files[ 0 ] );
					document.body.style.opacity = 1;
				}, false );
				//
				window.addEventListener( 'resize', onWindowResize, false );
			}
			function onWindowResize() {
				camera.aspect = window.innerWidth / window.innerHeight;
				camera.updateProjectionMatrix();
				renderer.setSize( window.innerWidth, window.innerHeight );
			}
			function onDocumentMouseDown( event ) {
				event.preventDefault();
				isUserInteracting = true;
				onMouseDownMouseX = event.clientX;
				onMouseDownMouseY = event.clientY;
				onMouseDownLon = lon;
				onMouseDownLat = lat;
			}
			function onDocumentMouseMove( event ) {
				if ( isUserInteracting === true ) {
					lon = ( onMouseDownMouseX - event.clientX ) * 0.1 + onMouseDownLon;
					lat = ( event.clientY - onMouseDownMouseY ) * 0.1 + onMouseDownLat;
				}
			}
			function onDocumentMouseUp( event ) {
				isUserInteracting = false;
			}
			function onDocumentMouseWheel( event ) {
				var fov = camera.fov + event.deltaY * 0.05;
				camera.fov = THREE.Math.clamp( fov, 10, 75 );
				camera.updateProjectionMatrix();
			}
			function animate() {
				requestAnimationFrame( animate );
				update();
			}
			function update() {
				if ( isUserInteracting === false ) {
					lon += 0.1;
				}
				lat = Math.max( - 85, Math.min( 85, lat ) );
				phi = THREE.Math.degToRad( 90 - lat );
				theta = THREE.Math.degToRad( lon );
				camera.target.x = 500 * Math.sin( phi ) * Math.cos( theta );
				//camera.target.y = 500 * Math.cos( phi ); // comment this to disable Y axis
				camera.target.z = 500 * Math.sin( phi ) * Math.sin( theta );
				camera.lookAt( camera.target );
				/*
				// distortion
				camera.position.copy( camera.target ).negate();
				*/
				renderer.render( scene, camera );
			}
		</script>
	</body>
</html>

所以现在你有一些神奇的东西可以给你一个HTML Table Row。例如:

function Book() {
    this.importableVariables = ['bookName', 'bookPrice', 'bookAuthor', 'bookComments'];
}
Book.prototype.toRow = function() {
    var output = '<tr>';
    for (var x in this.importableVariables) {
        var vName = this.importableVariables[x];
        output += '<td>' + this[vName] + '</td>';
    }
    output += '</tr>';
    return output;

}

第二步:执行XML Reader

这不是什么大问题。您可以更好地学习here。我只做例子。 就我而言,我想分两步来分割这一步。

步骤2.1:导入单行

这里我不在乎我在字符串中读到什么。我将在var book = new Book(); yourTableBodyJqueryRefference.append(book.toRow()); 上查找Book构造函数中列出的变量。因此,如果它存在,我们应该将该值导入我们的对象。

importableVariables

步骤2.2:完全导入

现在我们将做出最后的魔力。一种读取整个XML并拆分为N Book实例的函数。

Book.prototype.instanceFromXML = function(str) {
    var parser, doc;
    if(window.DOMParser) {
        parser = new DOMParser();
        doc = parser.parseFromString(str,"text/xml");
    } else {
        doc = new ActiveXObject("Microsoft.XMLDOM");
        doc.async = false;
        doc.loadXML(str);
    }
    for (var x in this.importableVariables) {
        var vName = this.importableVariables[x];
        var value = doc.getElementsByTagName(vName);
        this[vName] = value.length > 0 ? value[0].childNodes[0].nodeValue : '';
    }
}

最后的电话:

function readXML(str) {
    var parser, doc;
    if(window.DOMParser) {
        parser = new DOMParser();
        doc = parser.parseFromString(str,"text/xml");
    } else {
        doc = new ActiveXObject("Microsoft.XMLDOM");
        doc.async = false;
        doc.loadXML(str);
    }
    var xmlBooks = doc.getElementsByTagName("Book"), books = '';
    for (var i = 0; i < xmlBooks.length; i++) {
        var book = new Book();
        book.instanceFromXML(xmlBooks[i].childNodes[0].nodeValue);
        books += book.toRow();
    }
    return books;
}