求在网页上用javascript读写XML的最简单的例子

2024-11-25 13:01:42
推荐回答(2个)
回答1:

//把string转成xml对象
function loadXML(flag, xml) {
var xmlDoc;
if (window.ActiveXObject) {
var aVersions = ["MSXML2.DOMDocument.6.0", "MSXML2.DOMDocument.5.0", "MSXML2.DOMDocument.4.0", "MSXML2.DOMDocument.3.0", "MSXML2.DOMDocument", "Microsoft.XmlDom"];
for (var i = 0; i < aVersions.length; i++) {
try {
xmlDoc = new ActiveXObject(aVersions[i]);
break;
} catch (oError) {
}
}
if (xmlDoc != null) {
xmlDoc.async = false;
if (flag == true) {
xmlDoc.load(xml);
} else {
xmlDoc.loadXML(xml);
}
return xmlDoc.documentElement;
}
} else {
if (document.implementation && document.implementation.createDocument) {
xmlDoc = document.implementation.createDocument("", "", null);
if (xmlDoc != null) {
if (flag == true) {
xmlDoc.async = false;
xmlDoc.load(xml);
} else {
var oParser = new DOMParser();
xmlDoc = oParser.parseFromString(xml, "text/xml");
}
return xmlDoc.documentElement;
}
}
}
return null;
}

//下面这个例子是打开一个页面上传文件,返回的是一个xml,类似jpg...... 这样的string
$("#" + attachBtnClientID).click(function () {
var a = window.showModalDialog("../FileUpload.aspx", window, "center=1, resize=1");
if (a == null || a == "undefined") {
return;
}
var xml = loadXML(false, a);
if (xml == null) {
return;
}
var index = uploadCount++;
var idNode = loadXML(false, "" + index + "");
xml.appendChild(idNode);
uploadFileXml.appendChild(xml);
var path = xml.selectNodes("SavedFilename")[0].text;
var filename = xml.selectNodes("Filename")[0].text;
var filetype = xml.selectNodes("Type")[0].text;
var html = "";
html += "

";
html += "";
html += "
";
html += "";

$(html).appendTo($("#" + uploadedFileRowClientId));
$("#deleteuploadfile" + index).click(function () {
DeleteUploadedFile("uploadedfile" + index);
});

$("#" + uploadedFilesClientId).val(uploadFileXml.xml);
});

//下面是删除一个已经上传的文件,包括物理删除和在页面数据中删除
var uploadFileXml = loadXML(false, "");
var DeleteUploadedFile = function (id) {
var divId = "#" + id;
$(divId).hide();
var files = uploadFileXml.selectNodes("File");
for (var i = 0; i < files.length; i++) {
var idNode = files[i].selectSingleNode("ID");
var testId = "uploadedfile" + idNode.text;
if (testId == id) {
$.ajax({
url: "../Ajax.aspx",
type: "POST",
data: "action=deletefileonly&filename=" + files[i].selectSingleNode("SavedFilename").text,
dataType: "text",
error: function (xml) { alert("Error in Ajax Call" + xml); },
success: function (data) {
}
});
uploadFileXml.removeChild(files[i]);
}
}

回答2:








DSO示例





width="0" height="0">



















学生数据
姓名 年龄 班级