Search code examples
jqueryattributes

Can't retrieve attribute value from an XML element in jquery


I have xml that looks like this:

<marker>
        <name>Ada County Jail</name>
        <adr>Boise</adr>
        <state>Idaho</state>
        <geo>43.6073458, -116.2698884</geo>
        <tag>County</tag>
        <ice>t</ice>
        <url title="Ada County Jail">https://adacounty.id.gov/sheriff/ada-county-jail/</url>
        <url title="Inmates">https://apps.adacounty.id.gov/sheriff/reports/inmates.aspx</url>
</marker>

I'm using jquery. I pull out the URL elements here:

function parseXml(xml)
{
        $(xml).find("marker").each(function()
        {
         var url = $(this).find('url').map(function(i,v){return ($(v).text());}).get();
...

I'm trying to extract the text of the title attributes of the url elements so the HTML links look like this:

Link: Ada County Jail
Link: Inmates

This code fails with an unrecognized expression message:

for (i=0;i<url.length;i++){
      var web = url[i];
      var y = $(xml).find(url[1]).attr("title");
      html += '<a href="' + web + '">Link: ' + y + '</a>';
      }

This is my first time trying to access attributes. Help.


Solution

  • To extract the title attribute from the url elements you can modify your code like so:

    $xml.find("marker").each(function() {
      $(this).find('url').each(function() {
        const url = $(this).text();
        const title = $(this).attr('title');
        $('#links').append(`<a href="${url}">Link: ${title}</a><br>`);
      });
    });
    

    Here's a working example you can run on your machine:

    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <title>XML Parsing Test</title>
      </head>
      <body>
        <div id="links"></div>
    
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
        <script>
          const xmlString = `
            <marker>
              <name>Ada County Jail</name>
              <adr>Boise</adr>
              <state>Idaho</state>
              <geo>43.6073458, -116.2698884</geo>
              <tag>County</tag>
              <ice>t</ice>
              <url title="Ada County Jail">https://adacounty.id.gov/sheriff/ada-county-jail/</url>
              <url title="Inmates">https://apps.adacounty.id.gov/sheriff/reports/inmates.aspx</url>
            </marker>
          `;
    
          const xml = $.parseXML(xmlString);
          const $xml = $(xml);
    
          $xml.find("marker").each(function() {
            $(this).find('url').each(function() {
              const url = $(this).text();
              const title = $(this).attr('title');
              $('#links').append(`<a href="${url}">Link: ${title}</a><br>`);
            });
          });
        </script>
      </body>
    </html>
    

    If this doesn't fix your issue, or if anything is unclear, let me know in a comment and I'll revise my answer.