Solved

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

Posted on 2014-02-02
6
326 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Space-Age Communications Transitions to DevOps

ViaSat, a global provider of satellite and wireless communications, securely connects businesses, governments, and organizations to the Internet. Learn how ViaSat’s Network Solutions Engineer, drove the transition from a traditional network support to a DevOps-centric model.

 
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

Resolve Critical IT Incidents Fast

If your data, services or processes become compromised, your organization can suffer damage in just minutes and how fast you communicate during a major IT incident is everything. Learn how to immediately identify incidents & best practices to resolve them quickly and effectively.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
HTML5 storage and web apps 11 53
HTML question 2 28
HTML editor custom button 3 60
Slush on text 2 12
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
In this tutorial viewers will learn how to embed Flash content in a webpage using HTML5. Ensure your DOCTYPE declaration is set to HTML5: "<!DOCTYPE html>": Use the <object> tag to embed Flash content.: To specify that the object is Flash content, d…
The viewer will receive an overview of the basics of CSS showing inline styles. In the head tags set up your style tags: (CODE) Reference the nav tag and set your properties.: (CODE) Set the reference for the UL element and styles for it to ensu…

730 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