无法使用JavaScript在网页上加载XML文档

Cannot load XML documents on web page with JavaScript

本文关键字:加载 XML 文档 网页 JavaScript      更新时间:2023-12-25

我正在尝试加载解析XML文档,但HTML页面仍然为空,是不是我做错了什么。

index.html

<script type="text/javascript" src="assets/js/script.js"></script>
<body onLoad="outputXML('content', 'assets/xml/sample.xml', 'assets/xml/sample.xsl');"></body>

script.js

点击此处查看代码

sample.xml

<?xml version="1.0" encoding="utf-8"?>
<hitrecords>
  <record genre="Ska">
    <artist category="group" gender="male">Madness</artist>
    <title>Baggy Trousers</title>
    <length>
      <minutes>3</minutes>
      <seconds>30</seconds>
    </length>
  </record>
</hitrecords>

sample.xsl

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:template match="/">
        <xsl:for-each select="hitrecords/record">
            <p>
                <xsl:value-of select="."/>
                <xsl:value-of select="@genre"/> 
                <xsl:value-of select="artist"/> 
            </p>
        </xsl:for-each>
    </xsl:template> 
</xsl:stylesheet>

我刚刚测试了您的示例,它正在进行调整,以便将id="content"元素添加到HTML:中

<body onLoad="outputXML('content', 'assets/xml/sample.xml', 'assets/xml/sample.xsl');">
  <div id="content"></div>
</body>

content作为参数location的值来调用的function outputXML(location, xml, xsl) { ...}调用function processXML (location, xml, xsl) { ... }
此函数将resultDocument附加到具有值为location:的id的元素

document.getElementById(location).appendChild(resultDocument);