首页 > 解决方案 > 拆分和解析xml数据

问题描述

我正在从 xml 文件中检索一些数据并希望拆分结果,对其进行解析,然后将其打印到 html 元素中。

这是我的 xml 文件的示例:

<Root>
   <Foo>
      <Bar>
         <BarType>Green</BarType>
         <Date>2020-09-03 23:40:55</Date>
      </Bar>
   </Foo>
</Root>

我想从 Date 中拆分字符串并使其更具可读性。

所以不是“2020-09-03 23:40:55”,而是“2020 年 9 月 3 日 23:40”

到目前为止,这是我的功能:

function testFoo() {
    $.ajax({
        type: "GET",
        url: "/assets/TestFeed.xml",
        dataType: "xml",
        // Alert if error in reading xml
        error: function (e) {
            alert("An error occurred while processing XML file");
            console.log("XML reading Failed: ", e);
        },
        // Runs if xml read succesully
        success: function (response) {
            
            $(response).find("Foo").each(function () {
                // Finds Date in specific xml node
                var fooDate = $(this).find('Bar:has(BarType:contains("Green")) Date').text();
                
                // Test for console to make sure it works
                console.log(fooDate);
                
                // add to the HTML 
                $("p").append('<span class="date-text">' + "Last Updated:  " + '</span>' + '<span class="date-first">' + fooDate + '</span>' + '<span class="date-time">' + "at " + fooDate + '</span>');
            });
        }
    });
}

标签: javascriptjqueryajaxxml

解决方案


如果你可以使用momentjs

var response = '<Root>\
        <Foo>\
        <Bar>\
        <BarType>Green</BarType>\
        <Date>2020-09-03 23:40:55</Date>\
</Bar>\
</Foo>\
</Root>';

$(response).find("Foo").each(function () {
    var fooDate = $(this).find('Bar:has(BarType:contains("Green")) Date').text();
    

    // format date.....
    fooDate = moment(fooDate).format('MMM DD, YYYY \\a\\t HH:mm');

    console.log(fooDate);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>


推荐阅读