【问题标题】:How to convert xml into a 2d array in javascript?如何在javascript中将xml转换为二维数组?
【发布时间】:2022-10-14 14:59:48
【问题描述】:

我还需要将数组放入变量中。

我正在使用 .DataTable 进行分页,但它不接受使用 Javascript 从 xml 创建的表,根据这个https://datatables.net/forums/discussion/2689,我需要将我的 xml 转换为二维数组。

这是我的xml文件

<person>
    <data>
        <name>juan</name>
        <city>tokyo</city>
        <age>20</age>
        <sex>m</sex>
    </data>
    <data>
        <name>pedro</name>
        <city>manila</city>
        <age>22</age>
        <sex>m</sex>
    </data>
    <data>
        <name>maria</name>
        <city>bangkok</city>
        <age>23</age>
        <sex>f</sex>
    </data>
</person>

我的二维数组应该是这样的:

var person =[
    ["juan","tokyo","20","m"],
    ["pedro","manila","22","m"],
    ["maria","bangkok","23","f"],
];

这是我的 JavaScript 代码。输出显示在我的 html 页面上,但我不能将它用于 DataTable,这就是我需要将它存储在 javascript 数组中的原因。如何修改此代码以便将其放入变量而不是在 html 页面中显示?

function readperson(){
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function(){
        if (this.readyState == 4 && this.status ==200){
            writeperson(this);
        }
    }
    xmlhttp.open("GET", "person.xml", true);
    xmlhttp.send();
}

function writeperson(xml){
    var x,i,xmlDoc,txt,ths,trs,tre,the;
    xmlDoc = xml.responseXML;
    var person =xmlDoc.getElementsByTagName("data");
    var l = person.length;
    var nodes = person[0].childNodes[0];
    //var l3 = nodes[0].length;
    var l2 = person[0].childNodes[0].nodeValue;

    var arr = [];
    //orders.length = 3 since two <data> tag
     for(i=0; i < person.length; i++){
        //will add brackets inside the array arr
        arr.push([]);//example: if arr.push("hello") output is hello,hello,hello
        
        arr[i][0]=person[i].getElementsByTagName("name")[0].childNodes[0].nodeValue
        arr[i][1]=person[i].getElementsByTagName("city")[0].childNodes[0].nodeValue
        arr[i][2]=person[i].getElementsByTagName("age")[0].childNodes[0].nodeValue
        arr[i][3]=person[i].getElementsByTagName("sex")[0].childNodes[0].nodeValue
    }
    document.getElementById("person").innerHTML = arr;
}

当我使用 return 语句而不是 innerHTML 时,它不起作用。

我不知道我在做什么。我的教授甚至没有讨论 javascript 的基础知识,而是要求我们在一周内通过我们的输出。

更新我想到了。这是我的最终代码

$(document).ready(function () {
  $.ajax({
    type: "GET",
    url: "person.xml",
    dataType: "xml",
    success: function (xml) {
      const res = [];
      $(xml).find("person > data").each(function (i, person) {
          res.push([
            $(this).find("name", person).text(),
            $(this).find("city", person).text(),
            $(this).find("age", person).text(),
            $(this).find("sex", person).text(),
          ]);
        });

      $("#person_table").DataTable({
        data: res,
        columns: [
          { title: "Name" },
          { title: "Address" },
          { title: "Age" },
          { title: "Sex." },
        ],
      });
    },
  });
});

【问题讨论】:

    标签: javascript html jquery arrays


    【解决方案1】:

    这是另一个 Vanilla JS 使用 fetch()DOMParser()

    /* uncomment the next line for real application: */
    // fetch("person.xml").then(r=>r.text()).then(txt=>{
      const atts="name,city,age,sex".split(",");
    /* XML data string for SO demo, remove line for real application: */
      const txt = `<person><data><name>juan</name><city>tokyo</city><age>20</age><sex>m</sex></data><data><name>pedro</name><city>manila</city><age>22</age><sex>m</sex></data><data><name>maria</name><city>bangkok</city><age>23</age><sex>f</sex></data></person>`; 
    
      const xml=new DOMParser().parseFromString(txt,"text/html"),
        result=[...xml.querySelectorAll("data")].reduce((res,da)=>
          (res.push(atts.map(at=>da.querySelector(at).textContent)),res),
        []);
    // Test
      console.log(result);
    
    /* end of fetch(), uncomment next line for real application: */
    // });

    【讨论】:

    • 如何在 fetch() 函数之外分配结果变量?我尝试使用返回结果,然后声明 var dataSet = fetch()。然后我在我的 DataTable 上使用 dataSet 作为数据源,但它不起作用。
    • 这是关于异步处理的典型问题,请参阅此处的答案:stackoverflow.com/a/38869587/2610061
    【解决方案2】:

    您可以使用 jQuery(您的问题下方有此标签)来解析 html 标签。首先将 XML 数据字符串转换为 DOM HTML,然后按照常规使用 jQuery 的方式进行所有搜索和提取:

    // XML data string
    const xml = `
    <person>
        <data>
            <name>juan</name>
            <city>tokyo</city>
            <age>20</age>
            <sex>m</sex>
        </data>
        <data>
            <name>pedro</name>
            <city>manila</city>
            <age>22</age>
            <sex>m</sex>
        </data>
        <data>
            <name>maria</name>
            <city>bangkok</city>
            <age>23</age>
            <sex>f</sex>
        </data>
    </person>
    `;
    
    // Convert to DOM HTML
    const html = $.parseHTML(xml);
    
    // Set array for result
    const res = [];
    
    // Parse html, find data tags,
    // loop through it's content
    $(html).find("data").each(function() {
      // For each data element push
      // required data to array
      res.push([
        $(this).find("name").text(),
        $(this).find("city").text(),
        $(this).find("age").text(),
        $(this).find("sex").text()
      ]);
    });
    
    // Test
    console.log(res);
    &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt;

    【讨论】:

    • 当我的 xml 来自单独的 xml 文件时,我应该如何使用 $.parseHTML(xml)?
    • 您将数据作为xml 变量传递给writeperson 函数,请使用它。您可以尝试将所有这些代码放入 writeperson 函数中。也许您需要先提取xmlDoc = xml.responseXML; 并改用xmlDoc,做一些测试。
    • 或使用$.ajax 读取您的xml 文件,如下所示:stackoverflow.com/a/19220964/10917379
    【解决方案3】:

    考虑以下。

    示例:https://jsfiddle.net/Twisty/1vw3z6mf/

    JavaScript

    $(function() {
      function xmlToArray(xml) {
        var arr = [];
        $(xml).find("person > data").each(function(i, person) {
          arr.push([
            $("name", person).text(),
            $("city", person).text(),
            $("age", person).text(),
            $("sex", person).text()
          ]);
        });
        console.log("Converted", arr);
        return arr;
      }
    
      function writeperson(xml) {
        console.log("Write People");
        var people = xmlToArray(xml);
        $("#person").html(people);
      }
    
      function readperson() {
        console.log("Read People");
        $.get("person.xml", function(data) {
          writeperson(data);
        });
      }
    
      $("button").click(readperson);
    });
    

    jQuery 可以读取 XML,就像它可以读取 HTML 一样。因此,您可以使用 jQuery 选择器来遍历 XML。您可以使用.find()$("elem", object) 速记来执行此操作,它们是相同的。

    该逻辑遍历每个data 部分并在每个索引处创建数组。这为您提供了一个数组数组或数据表可以使用的二维数组。

    我清理了其他代码元素以全部使用 jQuery,但如果您选择使用 JavaScript 并没有错。

    【讨论】:

    • 我声明了 var dataSet = xmlToArray(xml);然后使用我的数据表上的 dataSet 变量作为数据源,但数据表似乎无法识别它。它在我的页面上显示了一个数组,但未应用数据表
    • @randomnamesksksk 你如何将数组传递给数据表?请提供一个最小的、可重复的示例:stackoverflow.com/help/minimal-reproducible-example
    猜你喜欢
    • 1970-01-01
    • 2021-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    • 1970-01-01
    • 2015-06-22
    • 1970-01-01
    相关资源
    最近更新 更多