我有一个XML,我需要使用javascript对其进行分组和显示。 如何解析xml,以便最终输出将是不同元素的计数。即。
XMlstring
txt = txt + "<FileList>";
txt = txt + "<File>";
txt = txt + "<FileID>1234</FileID>";
txt = txt + "<FileType>image</FileType>";
txt = txt + "<FileDateTime>201112345</FileDateTime>";
txt = txt + "<FileTitle>something1</FileTitle>";
txt = txt + "<FileSize>123</FileSize>";
txt = txt + "</File>";
txt = txt + "<File>";
txt = txt + "<FileID>1209</FileID>";
txt = txt + "<FileType>image</FileType>";
txt = txt + "<FileDateTime>201167890</FileDateTime>";
txt = txt + "<FileTitle>something1</FileTitle>";
txt = txt + "<FileSize>123</FileSize>";
txt = txt + "</File>";
txt = txt + "</FileList>";
Html我要显示
201112345 (1)
201167890 (1)
任何帮助将不胜感激,
谢谢,bhat
答案 0 :(得分:1)
您正在使用jQuery,因此您可以使用它来轻松访问XML的DOM。
以通常的方式为XML实例化一个jQuery包装器:
var $xml = $(txt);
然后,find所有<FileDateTime>
个孩子,并在对象中总结他们的内容:
var summary = { };
$xml.find('FileDateTime').each(function() {
// Get the element's content as text.
var dt = $.trim($(this).text());
// And update the summary
if(!summary.hasOwnProperty(dt))
summary[dt] = 0;
++summary[dt];
});
然后,您将摘要数据放在summary
。
实例:http://jsfiddle.net/ambiguous/gKgyr/
更新:基于this question about XML parsing in IE,我认为使用$.parseXML
会对IE有所帮助:
var $xml = $($.parseXML(txt));
我现在无法查看,但这是此版本的实时版本:http://jsfiddle.net/ambiguous/gKgyr/12/
答案 1 :(得分:1)
编辑:不适用于Internet Explorer。稍微增加一点支持。
没有jQuery的简单,未经优化的实现;
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(txt, "text/xml");
var dates = xmlDoc.evaluate("/FileList/File/FileDateTime/text()", xmlDoc, null, XPathResult.ANY_TYPE, null);
var result,
map = {},
summary = "";
while (result = dates.iterateNext()) {
var date = result.nodeValue.trim();
map[date] = map[date] ? ++map[date] : 1;
}
for(var key in map)
summary += key + " (" + map[key] + ")<br />";
document.getElementById("output").innerHTML = summary;
编辑:在Internet Explorer的支持下,它变得一团糟。如果可能,我会使用jQuery。
// Adding trim support to Internet Explorer ...
if(typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
}
}
var xpath = "/FileList/File/FileDateTime/text()",
map = {},
summary = "";
if (window.DOMParser) {
var parser=new DOMParser();
var xmlDoc = parser.parseFromString(txt,"text/xml");
var dates = xmlDoc.evaluate("/FileList/File/FileDateTime/text()", xmlDoc, null, XPathResult.ANY_TYPE, null);
var node;
while (node = dates.iterateNext()) {
var date = node.nodeValue.trim();
map[date] = map[date] ? ++map[date] : 1;
}
} else {
// Internet Explorer
var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(txt);
var dates = xmlDoc.selectNodes(xpath);
for (var i = 0; i < dates.length; i++) {
var date = dates[i].nodeValue.trim();
map[date] = map[date] ? ++map[date] : 1;
}
}
for(var key in map)
summary += key + " (" + map[key] + ")<br />";
document.getElementById("output").innerHTML = summary;