如何使用jQuery从XML中查找/提取数据 [英] How to find/extract data from xml with jQuery
问题描述
我正在尝试从下面的xml中提取StateLongName和StateShortName值.
I'm trying to extract the StateLongName and StateShortName values from the xml below.
我知道必须有一种简单而优雅的方法来使用jQuery.
I know there has to be a simple elegant way to do this with jQuery.
<NewDataSet>
<Table>
<StateLongName>Alabama</StateLongName>
<StateShortName>AL</StateShortName>
</Table>
<Table>
<StateLongName>Alaska</StateLongName>
<StateShortName>AK</StateShortName>
</Table>
...elments removed for brevity
</NewDataSet>
这就是我尝试过的.
从上方将xml加载到Javascript变量名称xml中.
Load the xml from above into a Javascript variable name xml.
尝试#1
$(xml).find("TABLE").each(function()
{
var stateName = $(this).find("StateLongName").innerText;
var stateCode = $(this).find("StateShortName").innerText;
});
尝试#1不会发现任何东西,也永远不会进入内部以加载stateName和stateCode变量.
Try #1 doesn't find anything and never goes inside to load the stateName and stateCode variables.
尝试#2
$(xml).find("StateLongName").each(function()
{
var stateName = $(this).find("StateLongName").innerText;
var stateCode = $(this).find("StateShortName").innerText;
});
尝试#2确实找到了匹配项,但是stateName和stateCode未定义.
Try #2 does find matches, however the stateName and stateCode are left undefined.
尝试#3
$(xml).find("StateLongName").each(function()
{
var stateName = $($(xml).find('StateLongName').parent()[0].innerHTML)[1].data;
var stateCode = $($(xml).find('StateLongName').parent()[0].innerHTML)[5].data;
});
尝试#3可行,但是必须有更好的方法.请赐教.
Try #3 works but there has to be a better way. Please enlighten me.
感谢您的时间!
推荐答案
它区分大小写,请像这样使用"Table"
:
It's case sensitive, use "Table"
like this:
$(xml).find("Table").each(function() {
var stateName = $(this).find("StateLongName").text();
var stateCode = $(this).find("StateShortName").text();
});
更新:抱歉,这有点令人困惑,请不要使用<table>
,它将它视为html创建<tbody>
的html,然后事情就从这里变得陌生:)如果将其更改为仅与其他任何东西相邻,它会起作用的,下面是将其更改为<tabl>
的示例: http://jsfiddle.net/Yvetc/
Update: Sorry this one was a bit baffling, don't use <table>
, it treats it as html creating a <tbody>
and things get stranger from there:) If you changed it to just abut anything else, it'll work, here's an example with it changed to <tabl>
: http://jsfiddle.net/Yvetc/
这里是完整的裸露测试页:
Here's a full bare test page:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
var xml="<NewDataSet><Tabl><stateLongName>Alabama</stateLongName><stateShortName>AL</StateShortName></Tabl><Tabl><StateLongName>Alaska</StateLongName><StateShortName>AK</StateShortName></Tabl></NewDataSet>";
$(xml).find("Tabl").each(function() {
var stateName = $(this).find("StateLongName").text();
var stateCode = $(this).find("StateShortName").text();
alert("State: " + stateName + " Code: " + stateCode);
});
</script>
</head>
<body>
</body>
</html>
这篇关于如何使用jQuery从XML中查找/提取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!