使用带有xmlDoc.getElementsByTagName的变量

时间:2013-06-23 22:11:54

标签: javascript xml variables

我正在尝试在JavaScript中使用日期变量来引用XML文档中的标记,然后在该标记内返回名为Current的属性的值。但没有成功。

我确信我只是遗漏了一些东西,却无法解决问题...非常感谢任何帮助。

<!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>

我的XML文件的摘录如下:

<?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>

1 个答案:

答案 0 :(得分:1)

getElementsByTagName返回元素集合(请注意s),因此您必须选择一个元素,然后获取其属性。

同时拥有数字标签名称可能会有问题

非数字标记http://jsfiddle.net/DT64U/

数字标记http://jsfiddle.net/DT64U/1