Pic*_*ico 6 xml jquery parsing cdata
我已经看到了处理这个问题的帖子,但我仍然无法解决我的问题:
我有CDATA的XML,当我解析XML时,它包含CDATA(我不想要).
XML示例:
<mainnav>
<nav path="/" xmlpath="home.xml" key="footer" navigator="">
<display><![CDATA[Home]]></display>
<title><![CDATA[Home]]></title>
</nav>
<nav path="/nav1/" xmlpath="nav1.xml" key="primary" navigator="primary" iconid="0">
<display><![CDATA[Nav 1]]></display>
<title><![CDATA[Nav 1]]></title>
<overdesc><![CDATA[test nav 1]]></overdesc>
<sub path="/nav1/sub1/" xmlpath="nav1/sub1.xml" key="sub">
<display><![CDATA[sub 1<br />of nav 1]]></display>
<title><![CDATA[sub 1<br />of nav 1]]></title>
</sub>
</nav>
<nav path="/nav1/" xmlpath="nav2.xml" key="primary" navigator="primary" iconid="1">
<display><![CDATA[Nav 2]]></display>
<title><![CDATA[Nav 2]]></title>
<overdesc><![CDATA[test nav 2]]></overdesc>
<sub path="/nav2/sub1/" xmlpath="nabv2/sub1.xml" key="sub">
<display><![CDATA[sub 1<br />of nav 2]]></display>
<title><![CDATA[sub 1<br />of nav2]]></title>
</sub>
</nav>
</mainnav>
Run Code Online (Sandbox Code Playgroud)
jQuery的:
$(document).ready(function(){
$.ajax({
type: "GET",
url: "site_xml/config.xml",
//contentType: "text/xml",
dataType: ($.browser.msie) ? "xml" : "text/xml",
success: parseXML,
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});});
function parseXML(xml) {
$(xml).find('nav').each(function(){
if ($(this).attr("key")=="primary") { // this is a primary nav item;
var title = $.trim( $(this).find('title').text() );
alert(title);
$("#output").append(title); //nothing showing up in my output DIV, presumably due to the CDATA tags?
}
});
Run Code Online (Sandbox Code Playgroud)
}
San*_*dro 10
看起来nav标签中有两个名为title的子项.当你这样做时,你会回来的:
$(this).find("title").text()
Run Code Online (Sandbox Code Playgroud)
尝试使用:
$(this).find("title:first").text()
Run Code Online (Sandbox Code Playgroud)
另外,删除条件:
dataType: ($.browser.msie) ? "xml" : "text/xml",
Run Code Online (Sandbox Code Playgroud)
并且只需使用:
dataType: "xml",
Run Code Online (Sandbox Code Playgroud)