简体   繁体   中英

Javascript Dynamic HREF Creation from XML Element Attribute Values

I want to use javascript to create dynamic HTML links from the attributes of an xml file.

I have used the following code to successfully write a list of all of the xml element atrributes (file names) I need to an HTML page, but now need to create links instead.

The anchor text of the links should be the XML element attributes (file names) that I had previously used document.write to write to my HTML page. An example of one of these file names from the xml file would be MyDocument.pdf

The href link should be made up of a text string prefix "file:///sdcard/portal/" then append the same xml element attributes (file names) to the end which makes up the link. An example of this would be file:///sdcard/portal/MyDocument.pdf

I've tried using the document.write method of creating a link but as I also need to use the (x[i].getAttributeNode("name").nodeValue) in the loop to return all of the attributes I'm struggling to make it work.

Thanks

<!DOCTYPE html>
<html>
<head>
<script src="myxml-loadxmldoc.js"> 
</script>

</head>
<body>

<script>
xmlDoc=loadXMLDoc("MyDocuments.xml");
x=xmlDoc.getElementsByTagName("file");

for (i=0;i<x.length;i++)
{

document.write(x[i].getAttributeNode("name").nodeValue);
document.write("<br>");

}

</script>

</body>
</html>

Try this, starting from right above the for loop.

var path = "file:///sdcard/portal/"; //this will be constant between all iterations
for (i=0;i<x.length;i++)
{
    var filename = x[i].getAttributeNode("name").nodeValue; //the nodefile is the filename
    document.write("<a href=" + path + filename + ">" + filename + "</a>");
    document.write("<br>");

}

That should end up giving you a tag that looks like this in your html:

<a href="file:///sdcard/portal/MyDocument.pdf">MyDocument.pdf</a>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM