4

I have some xml like the following:

<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>

How do I write the JavaScript to insert attributes on certain tags?

2
  • 2
    What's the scope here? Where and how do you read that XML? Commented Mar 6, 2011 at 13:53
  • Check out the Element interface in DOM 3 Core. It contains methods for setting attributes. Commented Mar 6, 2011 at 14:39

1 Answer 1

1

You can load the xml using XmlDOM, use XPath to find an element and then DOM manipulation to modify it:

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");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.