Solved

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

Posted on 2014-02-02
6
316 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 42

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
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
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 42

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

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Suggested Solutions

Not sure what the best email signature size is? Are you worried about email signature image size? Follow this best practice guide.
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
In this tutorial viewers will learn how to define a gradient in CSS. Create a new HTML document with an internal stylesheet.: Create a div in CSS and name it Gradient. Define the background as "linear-gradient(to right, #ee3668, black)". Ensure you …
In this tutorial viewers will learn how add a scalable full-width header using CSS3. Create a new HTML document with an internal stylesheet. Set a tiled background.:  Create a new div and name it Header. Position it with position:absolute at the top…

746 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now