javascript - 拆分和解析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>');
});
}
});
}
解决方案
如果你可以使用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>
推荐阅读
- loops - 为什么这个循环无限运行 discord.py?
- powershell - 在 powershell 脚本参数中包含换行符
- kotlin - 在 ContentConverter (ktor) 中解析 PartData
- mysql - SQL 合并两列
- laravel - 请求有文件不工作 - laravel
- firebase - 不确定长度的文本 Flutter
- graphql - 无法向 GraphQL 服务器发送请求
- azure-pipelines - Azure 管道,显示变量和分支的问题
- typescript - 打字稿:什么是异步函数定义语法?
- python - 如何在 docker selenium 中设置下载目录