0

I've read ~50 different threads on SO looking for the answer to this, and I've learned a bit about jquery and xml, but I haven't been able to translate any of it to what I'm doing or find anyone with quite the same issue. I'm trying to get the data of the the CDATA and write it into simple HTML table with the 'id' fields as the column titles.

Using an example, I have the following XML:

<?xml version="1.0" encoding="ISO-8859-1"?>
<catalog>
  <cd>
    <disk id="artist"><![CDATA[Mikey]]></disk>
    <disk id="title"><![CDATA[Greatest hits]]></disk>
    <disk id="year"><![CDATA[8675309]]></disk>
  </cd>
  <cd>
  .
  .

And the following code:

$(document).ready(function () {
  $.ajax({
      type:  "GET",
      url:  "catalog.xml",
      dataType:  "xml",
      success:  xmlParser
    });
  });

function xmlParser(xml) {
    $(xml).find("cd").each(function()( {
      $(".main").append('<div class="book"><div class="title">' + 
      $(this).find("disk:first").text() + '</div><div class="description">' + 
      $(this).find("disk:last").text() + '</div>');
    });
  }

I can get the first and last text out via this method, but I can't get anything in between, and this doesn't allow for any 'missing' fields in a record. I'd like to get the CDATA contents associated with the 'id' field values, but haven't been able to find a way to do this via jquery. Any help would be appreciated!! Thanks!

2
  • 2
    Check : stackoverflow.com/questions/652159/… Commented Dec 8, 2011 at 18:21
  • Have you tried using jQuery's attribute selector to access the elements by ID? (e.g: $(this).find('disk[id="artist"]').get(0).firstChild.nodeValue; Commented Dec 8, 2011 at 18:26

1 Answer 1

0
function xmlParser(xml) {
    var parts = ['artist', 'title', 'year'];

    $("cd", xml).each(function () {
        var $book = $('<div class="book">');

        for (var i=0; i<parts.length; i++) {
            $("<div>", {
                'class': parts[i],
                'title': parts[i],
                'text' : $("disk[id="+parts[i]+"]", this).text()
            }).appendTo($book);
        }
        $book.appendTo(".main");
    });
}
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.