How do I extract data from XML

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • spoken
    New Member
    • Oct 2007
    • 15

    How do I extract data from XML

    Hi,

    I quite new to Javascript and XML. Here a is snippet of my XML file.

    [CODE=xml]<xml>
    <cd>
    <rock>
    <item id='1'>
    <name>Bon Jovi</name>
    <price>$10</price>
    <description>ab c</description>
    </item>
    <item id='2'>
    <name>U2</name>
    <price>$11</price>
    <description>ab c</description>
    </item>
    <item id='3'>
    <name>Linkin Park</name>
    <price>$12</price>
    <description>ab c</description>
    </item>
    </rock>
    <pop>
    <item id='1'>
    <name>Nelly</name>
    <price>$5</price>
    <description>ab c</description>
    </item>
    <item id='2'>
    <name>Justin</name>
    <price>$5</price>
    <description>ab c</description>
    </item>
    </pop>
    </cd>
    </xml>
    [/CODE]
    I am working with javascript.
    Basically I have 2 problems.
    1. How do I just get the 'name' from all the items in <rock> tags?
    2. How do I get the the 'name' from a specific position node? For example, I want to get the name of the artist in <rock> from node 1 onwards. -> Expected output: U2, Linkin Park.

    Thanks so much in advance.

    Regards,
    Gordon
    Last edited by acoder; Oct 24 '07, 09:42 AM. Reason: Added code tags
  • dmjpro
    Top Contributor
    • Jan 2007
    • 2476

    #2
    actually where this file exists??

    debasis

    Comment

    • acoder
      Recognized Expert MVP
      • Nov 2006
      • 16032

      #3
      Gordon, welcome to TSDN!

      Check out this link. You'll want to make use of the document.getEle mentsByTagName( ) method.

      Comment

      • spoken
        New Member
        • Oct 2007
        • 15

        #4
        Hi acoder,

        I've seen that link. However, I just want to get the 'name' for the items in <rock>.
        I have tried
        xmldoc.getEleme ntsByTagName('i tems')
        but that gives me all the items, including those in <pop>.

        dmjpro,
        the file is a seperate xml and the javascript is in my html document. I manage to successfully load the xml already.

        Comment

        • dmjpro
          Top Contributor
          • Jan 2007
          • 2476

          #5
          Originally posted by spoken
          Hi acoder,

          I've seen that link. However, I just want to get the 'name' for the items in <rock>.
          I have tried
          xmldoc.getEleme ntsByTagName('i tems')
          but that gives me all the items, including those in <pop>.

          dmjpro,
          the file is a seperate xml and the javascript is in my html document. I manage to successfully load the xml already.

          have a look at this ............

          [code=javascript]
          var parent = xmldoc.getEleme ntsByTagName('r ock'); //get the parent node
          if(parent[0].childNodes.len gth){
          var child1 = parent[0].childNodes[0].getAttribute(' name'); //if there is any child nodes
          }
          [/code]

          have the same repetition ...... until the childnodes end.

          debasis

          Comment

          • spoken
            New Member
            • Oct 2007
            • 15

            #6
            Originally posted by dmjpro
            have a look at this ............

            [code=javascript]
            var parent = xmldoc.getEleme ntsByTagName('r ock'); //get the parent node
            if(parent[0].childNodes.len gth){
            var child1 = parent[0].childNodes[0].getAttribute(' name'); //if there is any child nodes
            }
            [/code]

            have the same repetition ...... until the childnodes end.

            debasis

            Hi debasis,

            Thanks for your reply.
            I've tried your code and I can't get any output. This is wat I wrote.

            [CODE=javascript]var parent = xmldoc.getEleme ntsByTagName('r ock'); //get the parent node
            alert(parent);
            if(parent[0].childNodes.len gth){
            var child1 = parent[0].childNodes[0].getAttribute(' name'); //if there is any child nodes
            }
            alert(child1);[/CODE]

            I get "HTMLCollection " for the first alert and nothing comes out for the second, and I'm using the exact XML file as above. I tried to print the whole xml file and it comes out fine.
            Last edited by gits; Oct 24 '07, 12:06 PM. Reason: added code tags

            Comment

            • gits
              Recognized Expert Moderator Expert
              • May 2007
              • 5390

              #7
              hi ...

              try the following adaption:

              [CODE=javascript]
              var p = xmldoc.getEleme ntsByTagName('r ock');

              alert(p);

              if (p[0].childNodes.len gth) {
              var child1 = p[0].getElementsByT agName('item')[0];
              var c_name = child1.getAttri bute('name');
              }

              alert(c_name);[/CODE]
              kind regards

              Comment

              • spoken
                New Member
                • Oct 2007
                • 15

                #8
                Originally posted by gits
                hi ...

                try the following adaption:

                [CODE=javascript]
                var p = xmldoc.getEleme ntsByTagName('r ock');

                alert(p);

                if (p[0].childNodes.len gth) {
                var child1 = p[0].getElementsByT agName('item')[0];
                var c_name = child1.getAttri bute('name');
                }

                alert(c_name);[/CODE]
                kind regards
                Hi Gits,

                I tried your code adaption. I can't do child1.getAttri bute('name') because name is not an attribute but a tag. However if I do child1.getAttri bute('id'), I can extract the ID of the item.

                But I need to get the value of the <name> tag.. :(

                This is driving me bonkes.. Thanks for the help...

                Regards,
                Gordon

                Comment

                • acoder
                  Recognized Expert MVP
                  • Nov 2006
                  • 16032

                  #9
                  Originally posted by spoken
                  Hi Gits,

                  I tried your code adaption. I can't do child1.getAttri bute('name') because name is not an attribute but a tag. However if I do child1.getAttri bute('id'), I can extract the ID of the item.
                  So, use getElementsByTa gName() again on child1 (which is item) to get the name. That would give you the first name. Use a loop to get all the names of all items.

                  Comment

                  • Ferris
                    New Member
                    • Oct 2007
                    • 101

                    #10
                    Hi

                    I just wrote a complete sample code for you~~ It takes me a little long time..

                    first:save your xml data to file :cd.xml
                    second:create a new html file, make sure these two files are in the same directory.
                    then:paste my code into html file.

                    end:open html file and click the button.


                    [HTML]
                    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                    "http://www.w3.org/TR/html4/loose.dtd">
                    <html>
                    <head>
                    <title>Untitl ed Document</title>
                    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
                    </head>
                    <script language="javas cript">
                    function readxml(xmlfile )
                    {
                    var xmlDoc;
                    if (window.ActiveX Object){
                    xmlDoc = new ActiveXObject(" Microsoft.XMLDO M");
                    xmlDoc.async=fa lse;
                    }
                    else if (document.imple mentation && document.implem entation.create Document){
                    xmlDoc= document.implem entation.create Document("","do c",null);
                    }
                    if (typeof xmlDoc!="undefi ned"){
                    xmlDoc.load(xml file);
                    }
                    if (window.ActiveX Object)
                    {
                    //for IE
                    var rock = xmlDoc.getEleme ntsByTagName("r ock")[0];
                    if (rock != null)
                    {
                    var rockitem = rock.getElement sByTagName("ite m");
                    for (var i=0;i<rockitem. length;i++)
                    {
                    var id = rockitem[i].getAttribute(" id");

                    var name = rockitem[i].getElementsByT agName("name")[0].firstChild.nod eValue;
                    var price = rockitem[i].getElementsByT agName("price")[0].firstChild.nod eValue;
                    var description = rockitem[i].getElementsByT agName("descrip tion")[0].firstChild.nod eValue;
                    document.getEle mentById("divro ck").innerHTM L += "item " + i + "<br />";
                    document.getEle mentById("divro ck").innerHTM L += "name:" + name + "<br />";
                    document.getEle mentById("divro ck").innerHTM L += "price:" + price + "<br />";
                    document.getEle mentById("divro ck").innerHTM L += "descriptio n:" + description + "<br />";
                    }
                    }
                    var pop = xmlDoc.getEleme ntsByTagName("p op")[0];
                    if (pop != null)
                    {
                    var popitem = pop.getElements ByTagName("item ");
                    for (var i=0;i<popitem.l ength;i++)
                    {
                    var id = popitem[i].getAttribute(" id");

                    var name = popitem[i].getElementsByT agName("name")[0].firstChild.nod eValue;
                    var price = popitem[i].getElementsByT agName("price")[0].firstChild.nod eValue;
                    var description = popitem[i].getElementsByT agName("descrip tion")[0].firstChild.nod eValue;
                    document.getEle mentById("divpo p").innerHTM L += "item " + i + "<br />";
                    document.getEle mentById("divpo p").innerHTM L += "name:" + name + "<br />";
                    document.getEle mentById("divpo p").innerHTM L += "price:" + price + "<br />";
                    document.getEle mentById("divpo p").innerHTM L += "descriptio n:" + description + "<br />";
                    }
                    }
                    }
                    else if (typeof xmlDoc!="undefi ned"){
                    // for firefox
                    xmlDoc.onload = function (){
                    var rock = xmlDoc.getEleme ntsByTagName("r ock")[0];
                    if (rock != null)
                    {
                    var rockitem = rock.getElement sByTagName("ite m");
                    for (var i=0;i<rockitem. length;i++)
                    {
                    var id = rockitem[i].getAttribute(" id");

                    var name = rockitem[i].getElementsByT agName("name")[0].firstChild.nod eValue;
                    var price = rockitem[i].getElementsByT agName("price")[0].firstChild.nod eValue;
                    var description = rockitem[i].getElementsByT agName("descrip tion")[0].firstChild.nod eValue;
                    document.getEle mentById("divro ck").innerHTM L += "<strong>it em</strong> " + i + "<br />";
                    document.getEle mentById("divro ck").innerHTM L += "<strong>na me</strong>:" + name + "<br />";
                    document.getEle mentById("divro ck").innerHTM L += "<strong>pr ice</strong>:" + price + "<br />";
                    document.getEle mentById("divro ck").innerHTM L += "<strong>descri ption</strong>:" + description + "<br />";
                    }
                    }
                    var pop = xmlDoc.getEleme ntsByTagName("p op")[0];
                    if (pop != null)
                    {
                    var popitem = pop.getElements ByTagName("item ");
                    for (var i=0;i<popitem.l ength;i++)
                    {
                    var id = popitem[i].getAttribute(" id");

                    var name = popitem[i].getElementsByT agName("name")[0].firstChild.nod eValue;
                    var price = popitem[i].getElementsByT agName("price")[0].firstChild.nod eValue;
                    var description = popitem[i].getElementsByT agName("descrip tion")[0].firstChild.nod eValue;
                    document.getEle mentById("divpo p").innerHTM L += "<strong>it em</strong> " + i + "<br />";
                    document.getEle mentById("divpo p").innerHTM L += "<strong>na me</strong>:" + name + "<br />";
                    document.getEle mentById("divpo p").innerHTM L += "<strong>pr ice</strong>:" + price + "<br />";
                    document.getEle mentById("divpo p").innerHTM L += "<strong>descri ption</strong>:" + description + "<br />";
                    }
                    }
                    };
                    }
                    }
                    </script>
                    <body>
                    <h1>read xml file</h1>
                    rock
                    <div id="divrock" style="margin-left:10px; "></div>
                    pop
                    <div id="divpop" style="margin-left:10px; "></div>
                    <input type="button" value="read" onclick="readxm l('cd.xml');"/>
                    </body>
                    </html>

                    [/HTML]



                    by the way:
                    1:the code can be run in IE and firefox.
                    2:pay attention to onclick="readxm l('cd.xml'); , the "cd.xml" will tell javascript where your xml file is.if your xml file isn't "cd.xml",ch ange the parameter.
                    3:pay attention to the following code,I guess these code are what you're looking for:

                    [HTML]
                    var rockitem = rock.getElement sByTagName("ite m");
                    for (var i=0;i<rockitem. length;i++)
                    {
                    var id = rockitem[i].getAttribute(" id");
                    var name =
                    rockitem[i].getElementsByT agName("name")[0].firstChild.nod eValue;
                    var price =
                    rockitem[i].getElementsByT agName("price")[0].firstChild.nod eValue;
                    var description =
                    rockitem[i].getElementsByT agName("descrip tion")[0].firstChild.nod eValue;
                    }
                    [/HTML]


                    hope it helps :)

                    Comment

                    • spoken
                      New Member
                      • Oct 2007
                      • 15

                      #11
                      Wow..
                      Thank you so much Ferris.. I was going around in endless circles trying to transverse my XML file.

                      I guess the code that I didn't manage to get was:

                      [CODE=javascript] var p = xmldoc.getEleme ntsByTagName('r ock');
                      if (p[0].childNodes.len gth) {
                      var child1 = p[0].getElementsByT agName('item')[0]; //child1 => item 0
                      var c_name = child1.getEleme ntsByTagName('n ame')[0].firstChild.nod eValue;
                      }
                      [/CODE]
                      Thanks again for your effort. I think I'm getting it a lil better now..

                      Regards,
                      Gordon
                      Last edited by gits; Oct 24 '07, 08:13 PM. Reason: added code tags

                      Comment

                      Working...