Как отобразить эти данные XML в таблице HTML? - PullRequest
1 голос
/ 23 апреля 2019

У меня большой набор данных XML, из которого мне нужны только определенные значения. В частности, мне нужно сообщение об ошибке подтверждения сценария jmeter.

Вот мой XML, желаемый результат - таблица с 2 строками. В первой строке 3 столбца с сообщением об ошибке, во второй строке 3 столбца с нулем:

<?xml version="1.0" encoding="UTF-8"?>
<testResults version="1.2">
<httpSample ts="1555683457534" lb="What is cocktail?">
  <assertionResult>
    <name>Intent</name>
    <failure>true</failure>
    <error>false</error>
    <failureMessage>ERROR: THIS IS THE TEXT I NEED IN THE TABLE</failureMessage>
  </assertionResult>
  <assertionResult>
    <name>Input</name>
    <failure>true</failure>
    <error>false</error>
    <failureMessage>ERROR: THIS IS THE TEXT I NEED IN THE TABLE</failureMessage>
  </assertionResult>
  <assertionResult>
    <name>Entity</name>
    <failure>true</failure>
    <error>false</error>
    <failureMessage>ERROR: THIS IS THE TEXT I NEED IN THE TABLE</failureMessage>
  </assertionResult>
</httpSample>
<httpSample ts="1555683467885" lb="What is coconut?">
  <assertionResult>
    <name>Intent</name>
    <failure>false</failure>
    <error>false</error>
    <failureMessage></failureMessage>
  </assertionResult>
  <assertionResult>
    <name>Input</name>
    <failure>false</failure>
    <error>false</error>
    <failureMessage></failureMessage>
  </assertionResult>
  <assertionResult>
    <name>Entity</name>
    <failure>false</failure>
    <error>false</error>
    <failureMessage></failureMessage>
  </assertionResult>
</httpSample>
</testResults>

Я работал над примером из W3Schools, но, поскольку моя структура XML отличается, я пытался изменить ее в соответствии со своими потребностями.

Моя проблема в том, что в каждой ячейке моей HTML-таблицы указано «null», когда мне нужно дать значение узла failureMessage. Поэтому я считаю, что я получаю значения XML неправильно (в цикле for). У меня есть некоторый опыт работы с Xpath, но я не могу получить значение узла через Javascript / HTML.

Вот мой HTML / Javascript

<!DOCTYPE html>
<html>
   <head>
      <meta charset="utf-8"/>
      <style>
         table,th,td {
         border : 1px solid black;
         border-collapse: collapse;
         }
         th,td {
         padding: 5px;
         }
      </style>
   </head>
   <body>
      <button type="button" onclick="loadXMLDoc()">Get my results</button>
      <br><br>
      <table id="demo"></table>
      <script>
         function loadXMLDoc() {
          var xmlhttp = new XMLHttpRequest();
          xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
              myFunction(this);
            }
          };

          xmlhttp.open("GET", "Assertion_Results.xml", true);
          xmlhttp.send();
         }
         function myFunction(xml) {
          var i;
          var xmlDoc = xml.responseXML;
          var table="<tr><th>Intent</th><th>Input</th><th>Entity</th></tr>";
          var x = xmlDoc.getElementsByTagName("httpSample");
          for (i = 0; i <x.length; i++) {
            table += "<tr><td>" +
            x[i].getElementsByTagName("assertionResult")[0].childNodes[3].nodeValue +
            "</td><td>" +
            x[i].getElementsByTagName("assertionResult")[1].childNodes[3].nodeValue +
            "</td><td>"+
            x[i].getElementsByTagName("assertionResult")[2].childNodes[3].nodeValue +
            "</td></tr>";
          }
          document.getElementById("demo").innerHTML = table;
         }
      </script>
   </body>
</html>

Извините, если это был многословный вопрос, который должен быть простым

TL; DR: Как мне получить отдельные failureMessage поля из моего XML?

1 Ответ

0 голосов
/ 24 апреля 2019

Одним из способов анализа XML является использование XSLT для преобразования XML и извлечения данных.

Я поместил XML и XSLT в HTML как сценарии, но вы можете загрузить их из внешних ресурсов.

function transformXML(xmlText, xsltText) {

  if (!(window.DOMParser && window.XSLTProcessor)) {
    return xmlText;
  }
  
  // Load the XSLT into a document
  var xsltDoc = new DOMParser().parseFromString(xsltText, "text/xml");

  var xslt = new XSLTProcessor();
  xslt.importStylesheet(xsltDoc);

  var xml = new DOMParser().parseFromString(xmlText.trim(), "text/xml");

  var transformedXml = xslt.transformToDocument(xml);

  return (!transformedXml) ? xmlText :
    new XMLSerializer().serializeToString(transformedXml);
}

function fnProcess(){
  
  var xmlText = $("#xml").text();
  var xslText = $("#xslt").text();
  var resultText = transformXML(xmlText,xslText);
  
  $("#result").html(resultText);
  
}
#result {padding:20px;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="fnProcess()">Process</button>
<div id="result"></div>

<!-- XML Code Here -->
<script type="text/xml" id="xml">
  <?xml version="1.0"?>
  <testResults version="1.2">
    <httpSample ts="1555683457534" lb="What is cocktail?">
      <assertionResult>
        <name>Intent</name>
        <failure>true</failure>
        <error>false</error>
        <failureMessage>ERROR: THIS IS THE TEXT I NEED IN THE TABLE</failureMessage>
      </assertionResult>
      <assertionResult>
        <name>Input</name>
        <failure>true</failure>
        <error>false</error>
        <failureMessage>ERROR: THIS IS THE TEXT I NEED IN THE TABLE</failureMessage>
      </assertionResult>
      <assertionResult>
        <name>Entity</name>
        <failure>true</failure>
        <error>false</error>
        <failureMessage>ERROR: THIS IS THE TEXT I NEED IN THE TABLE</failureMessage>
      </assertionResult>
    </httpSample>
    <httpSample ts="1555683467885" lb="What is coconut?">
      <assertionResult>
        <name>Intent</name>
        <failure>false</failure>
        <error>false</error>
        <failureMessage></failureMessage>
      </assertionResult>
      <assertionResult>
        <name>Input</name>
        <failure>false</failure>
        <error>false</error>
        <failureMessage></failureMessage>
      </assertionResult>
      <assertionResult>
        <name>Entity</name>
        <failure>false</failure>
        <error>false</error>
        <failureMessage></failureMessage>
      </assertionResult>
    </httpSample>
  </testResults>
</script>

<!-- XSLT Code Here -->
<script type="text/xml" id="xslt">
  <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:template match="/">
      <table border="1">
        <tr bgcolor="#9acd32">
          <th style="text-align:left">httpSample ts</th>
          <th style="text-align:left">httpSample lb</th>
          <th style="text-align:left">name</th>
          <th style="text-align:left">failure</th>
          <th style="text-align:left">failureMessage</th>
        </tr>
        <xsl:for-each select="testResults/httpSample/assertionResult">
          <xsl:if test="failure = 'true'">
            <tr>
              <td>
                <xsl:value-of select="../@ts" />
              </td>
              <td>
                <xsl:value-of select="../@lb" />
              </td>
              <td>
                <xsl:value-of select="name" />
              </td>
              <td>
                <xsl:value-of select="failure" />
              </td>
              <td>
                <xsl:value-of select="failureMessage" />
              </td>
            </tr>
          </xsl:if>
        </xsl:for-each>
      </table>
    </xsl:template>
  </xsl:stylesheet>
</script>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...