试图用JS解析XML ...无法正常工作

时间:2013-03-28 22:03:24

标签: javascript xml xml-parsing

我在使用jS解析XML时遇到问题。基本上,我想从RSS源中获取内容并自动将其发布到我的网站上。我没有表现出任何错误,但我可能错了。好吧,如果没有任何错误,我想我错了。有任何想法吗?

 <script type="text/javascript">
 var xmlDoc;
 function loadxml() {
  xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
  xmlDoc.async = false;
  xmlDoc.onreadystatechange = readXML;
  xmlDoc.load("test.xml");
}

function readXML()
{
   if(xmlDoc.readyState == 4)
   {
    //Using documentElement Properties
    //Output company
    alert("XML Root Tag Name: " + xmlDoc.documentElement.tagName);

    //Using firstChild Properties
    //Output year
    alert("First Child: " + xmlDoc.documentElement.childNodes[1].firstChild.tagName);

 //Using lastChild Properties
 //Output average
 alert("Last Child: " + xmlDoc.documentElement.childNodes[1].lastChild.tagName);

 //Using nodeValue and Attributes Properties
 //Here both the statement will return you the same result
 //Output 001
 alert("Node Value: " + xmlDoc.documentElement.childNodes[0].attributes[0].nodeValue);
 alert("Node Value: " + xmlDoc.documentElement.childNodes[0].attributes.getNamedItem("id").nodeValue);

 //Using getElementByTagName Properties
 //Here both the statement will return you the same result
 //Output 2000
 alert("getElementsByTagName: " + xmlDoc.getElementsByTagName("year")[0].attributes.getNamedItem("id").nodeValue);

 //Using text Properties
 //Output John
 alert("Text Content for Employee Tag: " + xmlDoc.documentElement.childNodes[0].text);

 //Using hasChildNodes Properties
 //Output True
 alert("Checking Child Nodes: " + xmlDoc.documentElement.childNodes[0].hasChildNodes);
 }
 }
 </script>
 </head>

 <body onload="loadxml();">

 </body>
 </html>

感谢您的帮助!

0 个答案:

没有答案