How to check if an element exist reading XML...

Discussion in 'Javascript' started by neousr@googlemail.com, Nov 12, 2005.

  1. Guest

    <record>
    <title>Lunar Park</title>
    <author>Bret Easton Ellis</author>
    <publisher></publisher>
    <year>2005</year>
    </record>

    xAuthor =
    x.getElementsByTagName("author")[0].firstChild.nodeValue
    xPublisher =
    x.getElementsByTagName("publisher")[0].firstChild.nodeValue

    I'm retrieving data from a xml file, and I need to display that data in
    a table, but as soon as I try to reference an element that it's empty
    the browser stops working...

    Is there any way to prevent this (so, to know wich elements are empty
    in a certain "record")?

    Thanks a lot in advance.
    , Nov 12, 2005
    #1
    1. Advertising

  2. RobG Guest

    wrote:
    > <record>
    > <title>Lunar Park</title>
    > <author>Bret Easton Ellis</author>
    > <publisher></publisher>
    > <year>2005</year>
    > </record>
    >
    > xAuthor =
    > x.getElementsByTagName("author")[0].firstChild.nodeValue
    > xPublisher =
    > x.getElementsByTagName("publisher")[0].firstChild.nodeValue
    >
    > I'm retrieving data from a xml file, and I need to display that data in
    > a table, but as soon as I try to reference an element that it's empty
    > the browser stops working...


    Yes, because if there is no firstChild, attempting to get its nodeValue
    will cause an error. You could try:

    var t = x.getElementsByTagName("author");
    xAuthor = (t[0] && t[0].firstChild)? t[0].firstChild.nodeValue : '';


    >
    > Is there any way to prevent this (so, to know wich elements are empty
    > in a certain "record")?


    A more robust solution is to write a getValue() function:

    xAuthor = getValue(x.getElementsByTagName("author"));


    and getValue() can be something like:

    function getValue(C){
    var val='';
    for (var i=0, len=C.length; i<len; ++i){
    val += C.nodeValue;
    }
    return val;
    }

    You may want to add some smarts to getValue() to manage different
    element types.



    --
    Rob
    RobG, Nov 12, 2005
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Y.S.
    Replies:
    3
    Views:
    976
    strajan
    Sep 17, 2003
  2. LT
    Replies:
    7
    Views:
    2,071
    Phlip
    Jul 25, 2004
  3. HANM
    Replies:
    2
    Views:
    683
    Joseph Kesselman
    Jan 29, 2008
  4. Markus Mohr
    Replies:
    7
    Views:
    226
    Thomas 'PointedEars' Lahn
    Nov 28, 2003
  5. Stefan Holdermans
    Replies:
    0
    Views:
    116
    Stefan Holdermans
    Apr 29, 2013
Loading...

Share This Page