ladders81
ladders81

Reputation: 51

Using a variable with xmlDoc.getElementsByTagName

I'm trying to use a date variable in JavaScript to reference a tag in an XML document and then return the value of an attribute called Current within that tag. But without success.

I'm sure I'm just missing something but can't work out what... Any help is very much appreciated.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script>
function loadXMLDoc(weekscalendar) {

    if (window.XMLHttpRequest) {
        xhttp=new XMLHttpRequest();

    } else {
        xhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xhttp.open("GET","weeks.xml",false);
    xhttp.send();
    return xhttp.responseXML;
}  
</script>
</head>
<body>
<script>
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();

if (dd < 10) {
    dd = '0' + dd;
}

if (mm < 10) {
    mm = '0' + mm;
}
today = dd + mm + yyyy;

xmlDoc=loadXMLDoc("weeks.xml");
x=xmlDoc.getElementsByTagName (today);

var week = x.getAttributeNode("Current").nodeValue; //the nodevalue is the week
document.write(week);

</script>
</body>
</html>

An extract of my XML file is below:

<?xml version="1.0" encoding="UTF-8"?>
<Portal>
<23062013   Current="Week 13 (23/06/2013 - 29/06/2013)" Last="Week 12 (16/06/2013 - 22/06/2013)" Next="Week 14 (30/06/2013 - 06/07/2013)" />
<24062013   Current="Week 13 (23/06/2013 - 29/06/2013)" Last="Week 12 (16/06/2013 - 22/06/2013)" Next="Week 14 (30/06/2013 - 06/07/2013)" />
</Portal>

Upvotes: 1

Views: 1641

Answers (1)

Musa
Musa

Reputation: 97672

getElementsByTagName returns a collection of elements (notice the s) so you have to select an element then get its attribute.

Also having numeric tag names might be problematic

non numeric tag http://jsfiddle.net/DT64U/

numeric tag http://jsfiddle.net/DT64U/1

Upvotes: 1

Related Questions