【问题标题】:How do I insert new attributes dynamically to xml tags using javascript?如何使用 javascript 向 xml 标签动态插入新属性?
【发布时间】:2011-03-06 13:47:32
【问题描述】:

我有一些像下面这样的xml:

<dict>
        <key>Track ID</key>
        <integer>4896</integer>
        <key>Name</key>
        <string>Let 'cha Boy Go (DIRTY) F/B.o.B</string>
        <key>Artist</key>
        <string>4-Ize</string>
        <key>Grouping</key>
        <string>www.2dopeboyz.com</string>
        <key>Genre</key>
        <string>Hip-Hop</string>
        <key>Kind</key>
        <string>MPEG audio file</string>
        <key>Size</key>
        <integer>5837048</integer>
        <key>Total Time</key>
        <integer>243121</integer>
        <key>Year</key>
        <integer>2010</integer>
        <key>BPM</key>
        <integer>80</integer>
        <key>Date Modified</key>
        <date>2010-09-05T05:51:23Z</date>
        <key>Date Added</key>
        <date>2010-09-04T15:37:43Z</date>
        <key>Bit Rate</key>
        <integer>192</integer>
        <key>Sample Rate</key>
        <integer>44100</integer>
        <key>Comments</key>
        <string>80.3</string>
        <key>Normalization</key>
        <integer>7646</integer>
        <key>Persistent ID</key>
        <string>D9FAAD3E0203FA18</string>
        <key>Track Type</key>
        <string>File</string>
        <key>Location</key>
    </dict>

如何编写 JavaScript 以在某些标签上插入属性?

【问题讨论】:

标签: javascript xml setattribute


【解决方案1】:

您可以使用XmlDOM 加载xml,使用XPath 查找元素,然后通过DOM 操作对其进行修改:

var xpath = "/dict/key[. = 'Name']";
var element = null;

// IE:
if (ie)
{
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async = "false";
    xmlDoc.loadXML("<dict><key>Track ID</key><integer>4896</integer><key>Name</key><string>Let 'cha Boy Go (DIRTY) F/B.o.B</string></dict>"); 

    // Find the element using xpath.
    var values = xmlDoc.selectNodes(xpath);
    element = values[0];
}
// Others:
else
{
    parser = new DOMParser();
    xmlDoc = parser.parseFromString("<dict><key>Track ID</key><integer>4896</integer><key>Name</key><string>Let 'cha Boy Go (DIRTY) F/B.o.B</string></dict>", "text/xml");

    // Find the element using xpath.    
    var values = xmlDoc.evaluate(xpath, xmlDoc, null, XPathResult.ANY_TYPE, null);
    element = values.iterateNext();
}

// Change/add the id of the selected element.
element.setAttribute("id", "aga");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-26
    • 1970-01-01
    • 2020-12-05
    • 2018-08-25
    • 2010-10-14
    • 2019-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多