将表数据转换为xml结构化数据

时间:2015-07-27 08:50:26

标签: javascript jquery xml

我坚持下面的要求,在这里我必须将所有表数据显示给xml结构化数据,我尝试使用以下内容,我得到了xml结构,但很难用下面的表头显示行数据< / p>

<rowset>
<row name='SequnceNumber'>
    <row>Item</row> 
    <row>Weight</row>   
    <row>LableNo</row>
    <row>Unitcost</row>
    <row>Delete</row>
</rowset>
<rowset>
<rowset name='1212121'>
    <Item>test1</Item>
    <Weight>3000</Weight>   
    <LableNo>test1</LableNo>    
    <Unitcost>test1</Unitcost>  
    <Delete>test1</Delete>
</rowset>

我尝试使用以下代码,

  $(document).ready(function(){
    $("#idXmlData").click(function(){
        var xmlStart =  "<?xml version=\"1.0\" encoding=\"UTF-8\">";
        var xml = xmlStart;
        $(".mutliple tr").each(function() {
        var cells = $("td", this);
        if (cells.length > 0) {
            xml +="<rowset name='" + cells.eq(0).text() + "'>\n";
            for (var i = 1; i < cells.length; ++i) {
                //var tableHeaders=["SequnceNumber","Item","Weight","LableNo","Unitcost","Delete"];
                //for(var j=0;j<tableHeaders.length;j++){
                    // xml += "\t<"+j+">" + cells.eq(i).text() + "</"+j+">\n";
                    xml += "\t<row>" + cells.eq(i).text() + "</row>\n";
                //}               
            }
            xml += "</rowset>\n";
        }
    });
    window.alert(xml);      
    }); 
  });

JS fiddle

1 个答案:

答案 0 :(得分:1)

如果您将table格式化为包含th的标题将会更容易,如下面的代码所示,因为将标题文本与其他行分开会使事情变得有点简单。

这里的JS就是这样:

$("#idXmlData").click(function(){
    var xmlStart =  "<?xml version=\"1.0\" encoding=\"UTF-8\">";
    var xml = xmlStart;
    var xmlFirstRowSet = "<rowset><row name='";
    var thArray = new Array();
    $('th').each( function(index) {
        thArray[index] = $(this).html();
    });
    xmlFirstRowSet = xmlFirstRowSet + thArray[0] + "'>";
    var headerRowSet='';

    for(var i=1; i< thArray.length; i++) {
      headerRowSet =  headerRowSet + "<row>" + thArray[i] + "</row>";
    }

    headerRowSet = headerRowSet + "</rowset>";
    xmlFirstRowSet = xmlFirstRowSet + headerRowSet;
    var bodyRowSet ='';

    $(".mutliple tbody tr").each(function() {
        bodyRowSet = bodyRowSet + "<rowset name='" + $(this).find('td').html() + "'>";
        $(this).find('td:not(:first-child)').each(function() {
           $td = $(this);
           var tdValue = $(this).html();
           var $th = $td.closest('table').find('th').eq($td.index()).html();
           bodyRowSet = bodyRowSet + "<" + $th + ">" + tdValue + "</" + $th + ">";  
        });
        bodyRowSet = bodyRowSet + "</rowset>";
    });

    xml = xmlStart + xmlFirstRowSet + bodyRowSet;
    console.log(xml);
    window.alert(xml);      
});

这是一个有效的 Fiddle