简体   繁体   English

jQuery遍历XML从具有特殊值的节点中查找父级和子级

[英]jQuery traversing XML find parent and children from node with spesific value

I need to traverse an XML file and select a specific node (and all its children) which contains a child node like 我需要遍历一个XML文件并选择一个特定的节点(及其所有子节点),其中包含一个子节点,例如

<ssn>11036026534</ssn>

My aim is to read out the data as $('username',this).text() such that I am able to get all child nodes from the selected 我的目的是将数据读取为$('username',this).text(),这样我就可以从所选对象中获取所有子节点

<person> and down.

I have tried multiple ways of traversing, with no success - the most recent: 我尝试了多种遍历方式,但都没有成功-最近:

$(xml).each('person').find('ssn'["06106131859"]).parent( function () {
              console.log('ssn match for person')
          });

(which also gave me a jquery error) and (这也给了我一个jquery错误)和

$(xml).find('ssn[06106131859]').parent().each( function () {...

I would greatly appreciate some help to move forward with this..have a great day! 我将不胜感激,在此方面取得的一些帮助。祝您有美好的一天!

<person personIdHRM="10945"></person>
<person personIdHRM="11538"></person>
<person personIdHRM="1346"></person>
<person personIdHRM="23456">
    <authentication>
        <userId>7260132</userId>
        <username>Petter Smart</username>
    </authentication>
    <employments>
        <employment>
        <employeeId>18220</employeeId>
        <employmentPercentage>100.0</employmentPercentage>
        <lastEmployeed>2003-11-12</lastEmployeed>
      <positions>
        <position isPrimaryPosition="false" validFromDate="2015-01-01">
            <positionPercentage>0.0</positionPercentage>
            <positionStartDate>2015-01-01</positionStartDate>
        </position>
        <position isPrimaryPosition="true" validFromDate="2015-01-01">
            <positionPercentage>100.0</positionPercentage>
            <positionStartDate>2015-01-01</positionStartDate>
        </position>
      </positions>
    <startDate>2003-11-12</startDate>
    </employment>
  </employments>
  <familyName>Hanson</familyName>
  <genderCode>FEMALE</genderCode>
  <givenName>Elizabeth</givenName>
  <hrmAuthentications />
  <ssn>06106131859</ssn>
</person>

You can use :has() to find an element which contains another. 您可以使用:has()查找包含另一个元素。 Try this: 尝试这个:

var $persons = $(xml).find('person:has(ssn)');
$persons.each(function() {
    var $ssn = $(this).find('ssn')
    console.log($ssn.text()); // == 06106131859 in your example
});

To select a specific person by the ssn value, try this: 要通过ssn值选择特定的person ,请尝试以下操作:

var $person = $(xml).find('person:has(ssn:contains("06106131859"))');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM