Solved

How to create a working hyperlink from text within an XML value using javascript

Posted on 2014-02-02
6
321 Views
Last Modified: 2014-02-10
This is something new for me so please be patient if I don't explain what I'm trying to do correctly.  I'm trying to use JavaScript to read the contents of an XML file and place them in an HTML table containing two columns and any number of rows.  The problem I'm encountering occurs when there is an hyperlink in the value being written into the table.  I need to end up with a working hyperlink but at this point I'm getting nothing at all.  Note that I have VERY MUCH simplified both the headline and the text node values to make this problem as simple as possible to understand.  In actual practice both of these nodes may contain several hyperlinks (or none at all).

XML
<?xml version="1.0" encoding="UTF-8"?>
<stories>
  <story>
    <headline>Headline number 1</headline>
    <text>
      Text number 1.  Please <a href='http://www.mysite.com/contactus.htm'>CONTACT US</a> if you have any questions.
    </text>
  </story>
  <story>
    <headline>Headline number 2</headline>
    <text>
      Text number 2.  Please <a href='http://www.mysite.com/directions.htm'>CLICK HERE</a> for directions to our location.
    </text>
  </story>
</stories>

Open in new window


HTML with JavaScript
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<body>

    <script>
        if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        }
        else {// code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.open("GET", "homecontent.xml", false);
        xmlhttp.send();
        xmlDoc = xmlhttp.responseXML;

        document.write("<table border='1'>");
        var x = xmlDoc.getElementsByTagName("story");

        for (i = 0; i < x.length; i++)
            if (i % 2==0)
            {
                document.write("<tr><td>");
                document.write(x[i].getElementsByTagName("headline")[0].childNodes[0].nodeValue);
                document.write("</td><td>");
                document.write(x[i+1].getElementsByTagName("headline")[0].childNodes[0].nodeValue);
                document.write("</td></tr>");
            }
            else
            {
                document.write("<tr><td>");
                document.write(x[i-1].getElementsByTagName("text")[0].childNodes[0].nodeValue);
                document.write("</td><td>");
                document.write(x[i].getElementsByTagName("text")[0].childNodes[0].nodeValue);
                document.write("</td></tr>");
            }
        
        document.write("</tr></table>");
    </script>

</body>
</html>

Open in new window


The result I'm trying to achieve is this (a table with two columns and any number of rows):

Headline 1                           Headline 2
Please CONTACT US if         Please click HERE for
you have any questions.     for directions to our location

(The words in capital letters above should be active hyperlinks that the reader can click on to visit the pages specified within the anchor tags.)

Thank you for the help and please let me know if you need any further explanation of the problem.
0
Comment
Question by:penlandt
  • 3
  • 2
6 Comments
 
LVL 35

Accepted Solution

by:
Robert Schutt earned 500 total points
ID: 39829045
Text nodes in xml should be encoded (&lt; and &gt; instead of < and >), in your example:
<?xml version="1.0" encoding="UTF-8"?>
<stories>
  <story>
    <headline>Headline number 1</headline>
    <text>
      Text number 1.  Please &lt;a href='http://www.mysite.com/contactus.htm'&gt;CONTACT US&lt;/a&gt; if you have any questions.
    </text>
  </story>
  <story>
    <headline>Headline number 2</headline>
    <text>
      Text number 2.  Please &lt;a href='http://www.mysite.com/directions.htm'&gt;CLICK HERE&lt;/a&gt; for directions to our location.
    </text>
  </story>
</stories>

Open in new window

However, if this is how you get the content delivered to you then a quick solution is this:
        for (i = 0; i < x.length; i++)
            if (i % 2==0)
            {
                document.write("<tr><td>");
                document.write(x[i].getElementsByTagName("headline")[0].innerHTML);
                document.write("</td><td>");
                document.write(x[i+1].getElementsByTagName("headline")[0].innerHTML);
                document.write("</td></tr>");
            }
            else
            {
                document.write("<tr><td>");
                document.write(x[i-1].getElementsByTagName("text")[0].innerHTML);
                document.write("</td><td>");
                document.write(x[i].getElementsByTagName("text")[0].innerHTML);
                document.write("</td></tr>");
            }

Open in new window

0
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 39829111
Have you considered using jQuery for this - makes life a whole lot easier (and no need to encode your XML):

$.ajax({
	type: "GET",
	url: "homecontent.xml",
	dataType: "xml",
	success: function(xml) {
		$(xml).find('story').each(function(){
			$('<p>').html( $('headline', this).html() ).appendTo('body');
			$('<p>').html( $('text', this).html() ).appendTo('body');
		});
	}
});

Open in new window

That's the working parts - I'll leave it to you to make your table :)
0
 
LVL 1

Author Comment

by:penlandt
ID: 39829617
Thank you Chris.  A caveman might make better progress using a rifle than a club but it takes time for that evolution to occur.  Meanwhile, he must eat.  

I know there are probably better ways to do what I'm trying to do but I have to start with what I understand and build from there.  I understand what I'm doing in the example I posted and I need to find a way to make that work.  Unfortunately, I don't yet understand what you've posted (I'll get there but I'm not there yet).  I will study it though and try to figure it out.  In the meantime, can anyone help me solve it my way?  Thanks again.
0
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 
LVL 1

Author Closing Comment

by:penlandt
ID: 39829642
Thank you Robert.  I didn't see your solution before I responded to Chris's.  It did exactly what I needed.  Now to start learning how to do it Chris's way. ;-)
0
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 39829668
While the caveman's trying to figure out how his club works, all the other cavemen have moved on to fine dining and are pointing and laughing at their club wielding friend :)

Once you figure out jQuery (not that hard, actually), you'll never look back and your apps will really start flying.

Good luck with it...
0
 
LVL 1

Author Comment

by:penlandt
ID: 39849273
I agree...I'm learning jQuery now.  I really do appreciate the help, I just had to understand what was happening so that I would then understand *why* jQuery would be a better solution.  There will be more questions. ;-)
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Find out what you should include to make the best professional email signature for your organization.
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
In this tutorial viewers will learn how to style elements, such a divs, with a "drop shadow" effect using the CSS box-shadow property Start with a normal styled element, such as a div.: In the element's style, type the box shadow property: "box-shad…
The viewer will the learn the benefit of plain text editors and code an HTML5 based template for use in further tutorials.

786 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question