JavaScript

超轻量级php框架startmvc

jQuery创建及操作xml格式数据示例

更新时间:2020-07-11 04:30:01 作者:startmvc
本文实例讲述了jQuery创建及操作xml格式数据。分享给大家供大家参考,具体如下:<!DOCTYPE

本文实例讲述了jQuery创建及操作xml格式数据。分享给大家供大家参考,具体如下:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery创建及操作xml</title>
</head>
<body>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script>
$(function(){
 var xmlDom=$($.parseXml("<?xml version=\"1.0\" encoding=\"utf-8\" ?><root><person></person></root>"));
 xmlDom.find("root").appendXml("<content/>").text("测试");
 xmlDom.find("content").beforeXml("<test/>");
 alert(xmlDom.xml());
});
(function($) {
 function mnpXml(opCode, xmlStr) {
 return this.each(function() {
 if (typeof xmlStr != "string") return;
 if (!jQuery.isXMLDoc(this)) return;
 var node = $.parseXml(xmlStr).firstChild.cloneNode(true);
 switch (opCode) {
 case "append":
 this.appendChild(node);
 break;
 case "prepend":
 if (this.childNodes.length > 0)
 this.insertBefore(node, this.firstChild);
 else
 this.appendChild(node);
 break;
 case "after":
 if (this.nextSibling)
 this.parentNode.insertBefore(node, this.nextSibling);
 else
 this.parentNode.appendChild(node);
 break;
 case "before":
 this.parentNode.insertBefore(node, this);
 break;
 }
 });
 }
 $.fn.extend({
 appendXml: function(s) {
 return mnpXml.call(this, "append", s);
 },
 prependXml: function(s) {
 return mnpXml.call(this, "prepend", s);
 },
 afterXml: function(s) {
 return mnpXml.call(this, "after", s);
 },
 beforeXml: function(s) {
 return mnpXml.call(this, "before", s);
 },
 xml: function() {
 var elem = this[0];
 return elem.xml || (new XMLSerializer()).serializeToString(elem) ;
 },
 innerXml: function() {
 var s = this.xml();
 var i = s.indexOf(">"), j = s.lastIndexOf("<");
 if (j > i)
 return s.substring(i + 1, j);
 else
 return "";
 }
 });
 $.extend(jQuery, {
 parseXml: function(xmlStr) {
 if (window.ActiveXObject) {
 var xd = new ActiveXObject("Microsoft.XMLDOM");
 xd.async = false;
 xd.loadXML(xmlStr);
 return xd;
 }
 else if (typeof DOMParser != "undefined") {
 var xd = new DOMParser().parseFromString(xmlStr, "text/xml");
 return xd;
 }
 else return null;
 },
 toXml: function(obj, nodeName, useAttr) {
 var x = $($.parseXml("<" + nodeName + " />"));
 var n = x.find(":first");
 for (var p in obj) {
 if (useAttr)
 n.attr(p, obj[p]);
 else
 n.appendXml("<" + p + " />").find(p).text(obj[p]);
 }
 return x[0];
 }
 });
 })(jQuery);
</script>
</body>
</html>

运行结果:

PS:这里再为大家提供几款关于xml操作相关在线工具供大家参考使用:

在线XML/JSON互相转换工具: http://tools.jb51.net/code/xmljson

在线格式化XML/在线压缩XMLhttp://tools.jb51.net/code/xmlformat

XML在线压缩/格式化工具: http://tools.jb51.net/code/xml_format_compress

xml代码在线格式化美化工具: http://tools.jb51.net/code/xmlcodeformat

jQuery 创建 操作 xml