2016-11-23 65 views
1

我有了一个给定结构(我不能改变它)的XMLE文档,它是这样的:jQuery的 - 如何访问多个XMLE孩子,一些具有相同名称的

<index> 
<letter> 
<title>A</title> 
<mainTerm> 
    <title>Some description</title> 
    <code>Q87.1</code> 
</mainTerm> 
<mainTerm> 
    <title>Another Description</title> 
    <see>Some reference to other entries</see> 
</mainTerm> 
<mainTerm> 
    <title>Another term<nemod>(-some) (detail)</nemod></title> 
    <code>F44.4</code> 
</mainTerm> 
<mainTerm> 
    <title>A more detailed term</title> 
    <seeAlso>similar terms</seeAlso> 
    <term level="1"> 
    <title>acute</title> 
    <code>R10.0</code> 
    </term> 
    <term level="1"> 
    <title>angina</title> 
    <code>K55.1</code> 
    </term> 
</mainTerm> 
</letter> 
</index> 

我是什么试图做的就是使用jQuery来访问这个文件的内容,并用它建立一个表格。

问题是我无法正常访问某些节点。

这里是jQuery来访问XML文件:

$.ajax({ 
url: 'index.xml', // name of file you want to parse 
dataType: "xml", 
success: parse, 
error: function(){alert("Error: Something went wrong");} 
}); 

这里是我试图用它来建表脚本:

function parse(document){ 
$(document).find("letter").each(function(){ 

$code = ($(this).find('code').text()); 
$desc = ($(this)).find('mainTerm->title').text(); 

//Build table 
$("#content").append(
    '<table><tr><th>Code</th><th>Description</th></tr><tr><td> '+$code+' </td> <td> '+$desc+' </td></tr></table>' 
);     
}); 
} 

的$ code变量的作品,但$ desc没有。我如何访问节点index->​​ letter-> mainTerm-> title的文本?请注意,还有一个名为“标题”的节点位于较高的位置,我不需要。

欣赏任何建议!

+1

试过吗? '$ desc = $(this).find('mainTerm title')。text();' – winseybash

+0

非常感谢@winseybash,它现在就开始了!这比我想象的要容易! – Cucurigu

回答

1

使用此:

$desc = $(this).find('mainTerm title').text(); 

它选择title所选择的项目的mainTerm元件内。

element selection上阅读更多。

+0

再次感谢@winseybash!感谢您的链接,这也是非常有用的,虽然我发现很难找到深入的教程,如何解析/处理复杂的XML文件,多个子节点... – Cucurigu

+0

@Cucurigu选择XML元素完成与HTML元素完全一样,所以应该有大量的教程。 – winseybash

相关问题