2013-08-29 61 views
1

假設我的XML文件使用VAR保存XML標籤數據到XML文件

sample.xml

<?xml version="1.0" encoding="utf-8"?> 
<api> 
    <category> 
     <id>1</id> 
     <title>title-1</title> 
     <mode /> 
    </category> 
    <category> 
     <id>2</id> 
     <title>title-2</title> 
     <mode /> 
    </category> 
    <category> 
     <id>3</id> 
     <title>title-3</title> 
     <!--store mode tag in xml--> 
     <mode> 
      <title>title-mod-1</title>   
      <id>mod-id</id> 
      <description>my own description</description> 
     </mode> 

     <!--end of mode tag--> 
    </category> 
</api> 

我的Ajax調用方法

$.ajax({ 
    type: "GET", 
    url: "sample.xml", 
    contentType: "text/xml", 
    dataType: "xml", 
    data: "", 
    crossDomain:true, 
    success: function(xml) { 

    $(xml).find('category').each(function(){ 

     var id=$(this).find('id').text();         
     var title=$(this).find('title').text(); 
        alert(id + ""+title);     //good 

        var my_mode= $(this).find('mode').text(); 
        alert(my_mode); 
        /* using this alert output some like that 
        title-mod-1 
        mod-id 
        my own description 
        */  

        /* but i require my output something like that 
        </mode> 
        <title>title-mod-1</title>   
        <id>mod-id</id> 
        <description>my own description</description> 
        </mode> 

        above output is store in xml file(modified.xml) in one variable and 
        able to use this xml file 
         */ 
        /*for those <mode /> have not any thing then nothing will be save*/       
     }); 
       }); 

回答

0

試試這個。

$.ajax({ 
    type: "GET", 
    url: "sample.xml", 
    contentType: "text/xml", 
    dataType: "xml", 
    data: "", 
    crossDomain:true, 
    success: function(xml) { 

    $(xml).find('category').each(function(){ 

     var id=$(this).find('id').text();         
     var title=$(this).find('title').text(); 
        alert(id + ""+title);     //good 

        var my_mode= $(this).find('mode').html(); //try this 
        // var my_mode= $(this).find('mode').parent().html(); //or try this 
        alert(my_mode); 
        /* using this alert output some like that 
        title-mod-1 
        mod-id 
        my own description 
        */  

        /* but i require my output something like that 
        </mode> 
        <title>title-mod-1</title>   
        <id>mod-id</id> 
        <description>my own description</description> 
        </mode> 

        above output is store in xml file(modified.xml) in one variable and 
        able to use this xml file 
         */ 
        /*for those <mode /> have not any thing then nothing will be save*/       
     }); 
       }); 

Demo link

+0

它不工作? –

+0

感謝您的迴應但方法不起作用。 var my_mode = $(this).find('mode')。html(); //試試這個 var my_mode = $(this).find('mode')。parent()。html(); –

+0

你有沒有使用我給出的代碼。它說什麼如果不工作? – anand4tech