jQuery实现的解析本地 XML 文档操作示例

2020-05-29 07:30:02易采站长站整理

本文实例讲述了jQuery实现的解析本地 XML 文档操作。分享给大家供大家参考,具体如下:

Create a jQuery object using an XML string and obtain the value of the title node.


<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.parseXML demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<p id="someElement"></p>
<p id="anotherElement"></p>

<script>
var xml = "<rss version='2.0'><channel><title>RSS Title</title></channel></rss>",
xmlDoc = $.parseXML( xml ),
$xml = $( xmlDoc ),
$title = $xml.find( "title" );

// Append "RSS Title" to #someElement
$( "#someElement" ).append( $title.text() );

// Change the title to "XML Title"
$title.text( "XML Title" );

// Append "XML Title" to #anotherElement
$( "#anotherElement" ).append( $title.text() );
</script>

</body>
</html>

方法二:


/**
* @param {String} xmlFileAddr 文件地址
*/
function parseXML(xmlFileAddr) {
$.ajax({
type: "GET",
url: xmlFileAddr,
dataType: "xml",
success: function(data, textStatus, jqXHR){//读取成功
console.log(data)
// todo......
},
error: function(jqXHR, textStatus, errorThrown) {//读取失败时
$.alert('解析文件失败!')
}
});
}

使用方法:


<script>

window.onload = function() {
parseXML("./xx/xx.xml"); //文件地址
}
</script>

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

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

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

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

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

更多关于jQuery相关内容感兴趣的读者可查看本站专题:《jQuery操作xml技巧总结》、《jQuery扩展技巧总结》、《jQuery常用插件及用法总结》、《jQuery常见经典特效汇总》及《jquery选择器用法总结》

希望本文所述对大家jQuery程序设计有所帮助。