将xml文件读入csv格式

时间:2017-10-12 22:44:39

标签: javascript jquery xml

我试图将以下xml内容解析为csv格式:

@flexible_decorator()
def f(foo):
    print(foo)


@flexible_decorator(arg="This is not default")
def g(bar):
    print(bar)

我能够使用FileApi读取xml文件。变量<order> <item>abc</item> <item>123</item> <item/> <item>000</item> </order> <order> <item>999</item> <item>333</item> </order> 包含xml内容。您能否提供一些有关如何将每个text标记解析为数组的见解?

&#13;
&#13;
<order>
&#13;
&#13;
&#13;

这是要在div <!doctype html> <html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="text/javascript"> $(function () { $("#fileUpload").change(function () { for (var i = 0; i < this.files.length; i++) { var reader = new FileReader(); reader.onload = function(e) { var text = reader.result; } reader.readAsText(this.files[i]); //TODO //1. find tag <order> //2. get all <item> text into an array //3. separate array elements with a semicolon //4. show array content in the div dataContainer + <br> //5. repeat until there is no more <order> tags to parse } }); }); </script> </head> <body> <input type="file" id="fileUpload" multiple="multiple" /> <div id="dataContainer"></div> </body> </html>中显示的预期输出:

dataContainer

2 个答案:

答案 0 :(得分:0)

为什么不将数据存储在Document中,并像对待任何其他DOM一样迭代它?你想做什么看起来有点像MDN's example of doing exactly that

var sMyString = '<a id="a"><b id="b">hey!</b></a>';
var oParser = new DOMParser();
var oDOM = oParser.parseFromString(sMyString, "text/xml");

orders = oDOM.getElementsByTagName("order");
for (i = 0; i < orders.length(); i++) {
    // Do stuff
}

或者如果您感觉更勇敢,可以使用XPath引用与oDOM对象。

答案 1 :(得分:0)

您可以使用.find()获取<order>个元素,.each()来迭代<item>元素,连接每个元素的.textContent

let xml = `<?xml version="1.0" encoding="UTF-8"?>
<root>
  <order>
    <item>abc</item>
    <item>123</item>
    <item/>
    <item>000</item>
  </order>
  <order>
    <item>999</item>
    <item>333</item>
  </order>
</root>`;

let str = "";

$(xml)
  .find("order")
  .each(function() {
    let item = $(this).find("item");
    item.each(function(i, el) {
      str += el.textContent + (i < item.length - 1 ? ";" : "");
    });
    str += "\n";
  });

console.log(str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>