我有一些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以在某些标签上插入属性?
答案 0 :(得分: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");