SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Evangelist NokX's Avatar
    Join Date
    Feb 2003
    Location
    Knoxville, TN
    Posts
    529
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Convert string into XML object

    i have a simple string that looks something like this...

    Code:
    var xml = "<mydata><name>Bob Smith</name><email>bob@smith.com</email></mydata>";
    i'd like to take this string and convert it so i can run things like...

    Code:
    var names = xml.getElementsById("name");
    var num_names = names.length;

  2. #2
    SitePoint Wizard gRoberts's Avatar
    Join Date
    Oct 2004
    Location
    Birtley, UK
    Posts
    2,439
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code HTML4Strict:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
        <head>
            <title>Untitled Document</title>
            <link rel="stylesheet" type="text/css" media="screen" />
            <script type="text/javascript">
                function parseXML(val) {
                    if (document.implementation && document.implementation.createDocument) {
                        xmlDoc = new DOMParser().parseFromString(val, 'text/xml');
                    }
                    else if (window.ActiveXObject) {
                        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                        xmlDoc.loadXML(val);
                    }
                    else
                    {
                        alert('Your browser can\'t handle this script');
                        return null;
                    }
                    return xmlDoc;
                }
                var xmlDoc;
                window.onload = function() {
                    xmlDoc = parseXML('<mydata><name>Bob Smith</name><email>bob@smith.com</email><name>Jon Doe</name><email>jon@doe.com</email></mydata>');
                    var items = xmlDoc.getElementsByTagName('name');
                    alert(items.length);
                    for(var i = 0; i < items.length; i++) {
                        alert(items[i].childNodes[0].nodeValue);
                    }
                };
            </script>
        </head>
        <body></body>
    </html>



Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •