HTML-файл DOM, ссылающийся на XML-файл, не будет печататься в браузере - PullRequest
0 голосов
/ 09 ноября 2010

Я абсолютно новичок в этом, и я беру урок для развлечения, который теперь превратился в большую головную боль. У меня есть этот HTML-файл DOM, который ссылается на файл XML, который мне нужен, чтобы показать на экране в браузере. Следует печатать только элементы, название, первое, последнее, местоположение, описание. CSS и Schema подтверждают правильность и работают. Должен ли я по-прежнему оставлять их обоих в файле XML, когда я использую файл HTML? Я получаю пустое на экране браузера. Спасибо, Лиам

<html>

<head>

    <title>Catalog</title>

    <script type="text/javascript">

         var xmlDoc;

         function loadXMLDoc() {

              // XML loader for IE

              if (window.ActiveXObject) {

                  xmlDoc = new ActiveXObject("Microsoft.XMLDOM");

                  xmlDoc.load("catalog.xml");

                 printCatalog();

            }

            // XML loader for other browsers

           else {

                xmlDoc = document.implementation.createDocument("", "", null);

                xmlDoc.load("catalog.xml");

                xmlDoc.onload = printCatalog;

          }
      }


      function printcatalog() {

          var titleNodes = xmlDoc.getElementsByTagName("title");

          var firstNodes = xmlDoc.getElementsByTagName("first");

          var lastNodes = xmlDoc.getElementsByTagName("last");

          var locationNodes = xmlDoc.getElementsByTagName("location");

         var descriptionNodes = xmlDoc.getElementsByTagName("description");

            for (var i = 0; i < titleNodes.length; i++) {

              document.write("<div style='font-family:arial; font-weight:bold;

                                      color:red'>" + 

                                    titleNodes[i].firstChild.nodeValue + "</div>");

              document.write("<div style='font-family:arial'>" +

                                     firstNodes[i].firstChild.nodeValue + "<br />");

              document.write(lastNodes[i].firstChild.nodeValue + "<br />");

             document.write(firstNodes[i].firstChild.nodeValue + "<br />");

             document.write(locationNodes[i].firstChild.nodeValue + "<br />");

             document.write(descriptionNodes[i].firstChild.nodeValue + "</div>");
           }


       }

 </script>

 </head>

<body onload="loadXMLDoc()">

</body>

</html>







 <?xml version="1.0"?>

 <?xml-stylesheet href="catalog.css" type="text/css"?>

 <catalog xmlns:xs="http://www.w3.org/2001/XMLSchema-instance"

 xs:noNamespaceSchemaLocation="catalog.xsd"> 

 <course courseNum="CS205" area="ComputerScience">

 <title>Programming 1</title>

 <instructor>

 <first>Bill</first>

 <last>Gates</last>

 </instructor>

 <units>3</units>

<location>

<building>100</building>

<room>101</room>

</location>

 <description>Learn from the man himself, Mr. Microsoft. 

             Must love PCs and not Macs.</description>

</course>

<course courseNum="SS305" area="SocialStudies">

<title>Government 1945</title>

<instructor>

 <first>Karl</first>

 <last>Marx</last>

 </instructor>

<units>3</units>

<location>

<building>200</building>

<room>202</room>

</location>

<description>Mr. Marx will explain his political theories

          Lecture course. Bring lots of coffee.</description>
 </course>

<course courseNum="MA350" area="Math">

<title>Math 911</title>

 <instructor>

 <first>Albert</first>

 <last>Einstein</last>

 </instructor>

 <units>3</units>

<location>

<building>200</building>

 <room>302</room>

</location>

 <description>Find the answers to the universe in just one semester.

  </description>

</course>

  </catalog>

1 Ответ

0 голосов
/ 09 ноября 2010

Вы не можете использовать document.write после загрузки страницы, поскольку она будет перезаписывать уже загруженный DOM.

Вы должны сделать что-то вроде:

<body>
   <script> 
       loadXMLDoc(); // call it while the page is loading
   </script>
</body>

Или, если вы не хотите вызывать loadXMLDoc ();рано, вы можете изменить document.write на что-то другое.Может быть уродливая версия:

document.body.innerHTML += 'somestuff'

Или добавить текстовые узлы к телу:

var doc = document.createTextNode('text here');
document.body.appendChild(doc);
...