2013-01-08 57 views
0

這裏是XML文件:如何獲取XML標記內的內容以創建數組?

<SketchPad> 
<Player> 
    <TotalPage>2</TotalPage> 
    <BackgroundImage>/Users/ltlab/Library/Application Support/iPhone Simulator/5.1/Applications/D84490FE-3450-456C-A8FE-16BE8B1EB12C/Documents/publicUser_1356864779.441782_local.png</BackgroundImage> 
    <Name>1</Name> 
    <SelfBackgroundImage>sound.png</SelfBackgroundImage> 
    <Type>Record</Type> 
    <X_Value>0.000000</X_Value> 
    <Y_Value>38.000000</Y_Value> 
    <Height_Value>50.000000</Height_Value> 
    <Width_Value>50.000000</Width_Value> 
    <File_Path>null</File_Path> 
</Player> 
<Player> 
    <TotalPage>2</TotalPage> 
    <BackgroundImage>/Users/ltlab/Library/Application Support/iPhone Simulator/5.1/Applications/D84490FE-3450-456C-A8FE-16BE8B1EB12C/Documents/publicUser_1356864779.441782_local.png</BackgroundImage> 
    <Name>1</Name> 
    <SelfBackgroundImage>8_128x128.png</SelfBackgroundImage> 
    <Type>Stamp</Type> 
    <X_Value>7.000000</X_Value> 
    <Y_Value>716.000000</Y_Value> 
    <Height_Value>80.000000</Height_Value> 
    <Width_Value>80.000000</Width_Value> 
    <File_Path>null</File_Path> 
</Player> 
<Player> 
    <TotalPage>2</TotalPage> 
    <BackgroundImage>/Users/ltlab/Library/Application Support/iPhone Simulator/5.1/Applications/D84490FE-3450-456C-A8FE-16BE8B1EB12C/Documents/publicUser_1356864779.441782_local.png</BackgroundImage> 
    <Name>1</Name> 
    <SelfBackgroundImage>duck.png</SelfBackgroundImage> 
    <Type>Stamp</Type> 
    <X_Value>570.000000</X_Value> 
    <Y_Value>715.000000</Y_Value> 
    <Height_Value>80.000000</Height_Value> 
    <Width_Value>80.000000</Width_Value> 
    <File_Path>null</File_Path> 
</Player> 
</SketchPad> 


我想要做的就是收集標籤內的所有數據。

$(xml).find("X_Value").toArray(); 

但它返回一個數組仍然包含標籤是這樣的:

[<x_value>0.0000000<x_value>,<x_value>7.0000000<x_value>,<x_value>570.0000000<x_value>]

不是預期的數組: [0.0000000,7.0000000,570.0000000]

我該怎麼做才能直接提取裏面的值標籤,製作一個數組?我不知道如何操作jQuery.map()

回答

3

使用此,而不是...

$(xml).find("X_Value").map(function() { return $(this).text(); }).get(); 

你前面的例子越來越對這些元素的引用。這用內部文本取代了引用。

+0

是否$(this)引用了 0.0000000 ?和「.text()」獲取內容:「0.0000000」。在每次迭代中,方法get()都會收集這些值嗎?但是我在這裏看不到任何數組聲明。我可以寫var變量content_arr = $(xml).find(「X_Value」)。map(function(){return $(this).text();})。get();創建目標數組? – Stallman

+0

@Stallman是的。地圖用返回值替換它的插槽。 'get()'只是獲取數組的廉價方法,'toArray()'(就像你的例子)也可以工作。 – alex

+0

你說get()只是一個獲取數組的廉價方法,但是如果我們不聲明一個變量來接收數組呢?在這種情況下,我們可以操縱數據數組。我想。謝謝回覆。 – Stallman