jQuery:仅在第一级子级中查找(XML)

时间:2016-06-14 16:31:52

标签: jquery xml

我们如何限制查找仅在XML文档中搜索第一级子项。

例如:

考虑这个XML,它是来自Onet webservice(https://services.onetcenter.org/developer/

的响应
<?xml version="1.0" encoding="UTF-8"?>
<report code="27-2011.00">
    <career>
        <code>13-2011.01</code>
        <title>Accountants</title>
        <tags bright_outlook="true" green="false" apprenticeship="false"/>
        <also_called>
            <title>Accountant</title>
            <title>Accounting Manager</title>
            <title>Certified Public Accountant (CPA)</title>
            <title>Staff Accountant</title>
        </also_called>
        <what_they_do>Analyze financial information and prepare financial reports to determine or maintain record of assets, liabilities, profit and loss, tax liability, or other financial activities within an organization.</what_they_do>
        <on_the_job>
            <task>Prepare, examine, or analyze accounting records, financial statements, or other financial reports to assess accuracy, completeness, and conformance to reporting and procedural standards.</task>
            <task>Report to management regarding the finances of establishment.</task>
            <task>Establish tables of accounts and assign entries to proper accounts.</task>
        </on_the_job>
        <resources>
            <resource href="https://services.onetcenter.org/ws/mnm/careers/13-2011.01/knowledge">
                <title>Knowledge</title>
            </resource>
..........................
..........................
.............................
    </explore_more>
    <where_do_they_work>
        <industry href="https://services.onetcenter.org/ws/mnm/browse/54" percent_employed="33">
            <code>54</code>
            <title>Professional, Science, &amp; Technical</title>
        </industry>
    </where_do_they_work>
</report>

这里我试图在模态对话框上布局这些数据。因此,我需要处理每个节点。

首先,我需要找到标题。所以我尝试了这段代码。

var career = $(xml).find('career');

然后我将标题标记文本内容分配给标题字段

因此我使用

编码
$('#myh4').html($(career).find('title').text());

但显然它将所有标题标记文本分配给标题。

所以简单的问题是我们如何才能将查找功能仅限于第一级孩子。意味着如何防止它进入下一级别的孩子,如 also_called

1 个答案:

答案 0 :(得分:1)

使用.children('title').text() instead

  

.children()方法与.find()的区别仅在于.children()   在.sind()可以遍历时沿DOM树向下移动一个级别   在多个级别选择后代元素(孙子,   等)。