简体   繁体   English

如何使用javascript访问XML子节点

[英]how to access XML subnodes using javascript

I want to use javascript to get information from a xml file loaded into a webpage. 我想使用javascript从加载到网页中的xml文件中获取信息。

The below given is the xmlfile(a.xml) i am using. 下面给出的是我正在使用的xmlfile(a.xml)。

a.xml xml文件

<?xml version="1.0"?>

<Step rID="T6">
  <Obj ><![CDATA[Get Data Table - Passed]]></Obj>
  <Details ><![CDATA[]]></Details>
  <Time><![CDATA[7/5/2018 - 13:16:26]]></Time>
  <TimeTick>1530810986</TimeTick>
  <NodeArgs eType="User" icon="5" nRep="9" >
    <Disp><![CDATA[Get Data Table - Passed]]></Disp>
  </NodeArgs>
</Step>
<Step rID="T7">
  <Obj ><![CDATA[GetDataTable - Successful]]></Obj>
  <Details ><![CDATA[Toral Row get:65534]]></Details>
  <Time><![CDATA[7/5/2018 - 13:16:26]]></Time>
  <TimeTick>1530810986</TimeTick>
  <NodeArgs eType="User" icon="5" nRep="10" status="Passed" >
    <Disp><![CDATA[GetDataTable - Successful]]></Disp>
  </NodeArgs>
</Step>

I want to access nodes under a specific node in xml using java script? 我想使用Java脚本访问xml中特定节点下的节点吗? That is i want to access Time node after i access step node. 那就是我要在访问步骤节点之后访问“时间”节点。 And the below given is the index.html page to which i want to load the xml data 而下面给出的是我想将xml数据加载到的index.html页面

index.html index.html

<html>
  <head>
    <title>Report</title>
    <style></style>
  </head>
  <body>
    <p>Results of  <b>Test cases</b> </p>
    <div id="books"></div>
  </body>

  <script>
  var oXHR = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
  var testcase_Number = 0;
  var endOfTest= 0;
  function reportStatus() {
    if (oXHR.readyState == 4)               // REQUEST COMPLETED.
      showTheList(this.responseXML);      // ALL SET. NOW SHOW XML DATA.
  }

  oXHR.onreadystatechange = reportStatus;
  oXHR.open("GET", "a.xml", true);      // true = ASYNCHRONOUS REQUEST 
                                   //(DESIRABLE), false = SYNCHRONOUS REQUEST.
  oXHR.send();

  function showTheList(xml) {
    var divBooks = document.getElementById('books');        // THE PARENT DIV.
    var Book_List = xml.getElementsByTagName('Step');       // THE XML TAG NAME.
    var divLeft = document.createElement('div');
    divLeft.className = 'col1';

    for (var i = 0; i < Book_List.length; i++) {
      divLeft.innerHTML=Book_List[i].getChildElementsByTagName("Time")[0].nodeValue;
      divBooks.appendChild(divLeft);
    }
  };
  </script>
</html>

In the above code I am trying to access the Time subnode under the step node. 在上面的代码中,我试图访问step节点下的Time子节点。 and I have used arrays in the above example as the xml page i am using have lots of Step subnodes , and i want to access the Time subnodes under Step for each one of them. 并且我在上面的示例中使用了数组,因为我使用的xml页面具有很多Step子节点,并且我想为每个子节点访问Step下的Time子节点。

thanks, Any help is appreciated 谢谢,任何帮助表示赞赏

You have the option of iterating over the xml nodes directly, employing one of the XPath processing APIs . 您可以选择使用XPath处理API之一直接遍历xml节点。 It basically suffices to rewrite your showTheList function. 基本上可以重写showTheList函数。 What follows is a complete standalone solution, however: 但是,下面是一个完整的独立解决方案:

<html>
    <head>
    <title>Report</title>
    <style>

    </style>
    <script>
        function showTheList() {
            let x_xmlisland = document.getElementById("template_xml");
            let s_xmlsource = x_xmlisland.textContent; 

            // Parse xml. This may beunnecessary depending on the ajax lib used. 
            let parser = new DOMParser();
            let xmlDoc = parser.parseFromString(s_xmlsource, "application/xml");

            // Obtain the xml node set containing the needed info.
            // In this case, these are the textual contents of all 'Time' elements that are children of a 'Step' node.
            let xpr_time  = xmlDoc.evaluate("//Step/Time/text()", xmlDoc, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
            let node_time
              ;

            let divBooks = document.getElementById('books');        // THE PARENT DIV.
// debugger; // uncomment for tracing 
            while ( ( node_time = xpr_time.iterateNext() ) !== null ) { // iterate over xml nodes
                let divLeft = document.createElement('div');
                divLeft.className = 'col1';
                divLeft.innerHTML = node_time.textContent;  // The xpath expression references the 'text()' function which provides a text node. String must still be extracted. 
                divBooks.appendChild(divLeft);
            }
        }
        </script>
    </head>
    <body onLoad="showTheList()">
        <script type="text/xml" id="template_xml"><?xml version="1.0"?>
<Steps>
    <Step rID="T6">
        <Obj ><![CDATA[Get Data Table - Passed]]></Obj>
        <Details ><![CDATA[]]></Details>
        <Time><![CDATA[7/5/2018 - 13:16:26]]></Time>
        <TimeTick>1530810986</TimeTick>
        <NodeArgs eType="User" icon="5" nRep="9" >
            <Disp><![CDATA[Get Data Table - Passed]]></Disp>
        </NodeArgs>
    </Step>
    <Step rID="T7">
        <Obj ><![CDATA[GetDataTable - Successful]]></Obj>
        <Details ><![CDATA[Toral Row get:65534]]></Details>
        <Time><![CDATA[7/5/2018 - 13:16:27]]></Time>
        <TimeTick>1530810986</TimeTick>
        <NodeArgs eType="User" icon="5" nRep="10" status="Passed" >
            <Disp><![CDATA[GetDataTable - Successful]]></Disp>
        </NodeArgs>
    </Step>
</Steps>
        </script>
        <p>Results of  <b>Test cases</b> </p>
        <div id="books"></div>
    </body>
</html>

Code has been tested. 代码已经过测试。

Note 注意

The sample xml provided in the question is not well-formed since it lacksa unique root element. 问题中提供的示例xml格式不正确,因为它缺少唯一的根元素。 The solution would still work but only consider the first Step element. 该解决方案仍然有效,但仅考虑Step元素。

Update 更新资料

To allow for xml from an external source, the ajax code needs to be reintroduced: 为了允许来自外部源的xml,需要重新引入ajax代码:

function getData() {
    let oXHR = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
    oXHR.onreadystatechange = function() {
        if (oXHR.readyState == 4 && oXHR.status == 200) {
            showTheList(oXHR);
        }
    };
    oXHR.open("GET", "state_data.xml", true); // ...or whatever else
    oXHR.send();
} // getData

Lacking local data, it makes no longer sense to register showTheList as an onLoad handler. 缺少本地数据,将showTheList注册为onLoad处理程序不再有意义。

<body onLoad="getData()">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM