2017-10-12 82 views
0

我有一些XML结构如下:查找XML元素与特定的值与jQuery

<pressureVessel> 
    <closure1> 
    <topClosure> 
     <ellipsoidalHead> 
     <standardComponentData> 
      <identifier>Ellipsoidal Head #1</identifier> 
      <idNumber>1111</idNumber> 
      ... 
     </standardComponentData> 
     </ellipsoidalHead> 
    </topClosure> 
    </closure1> 
    <closure2> 
    <bottomClosure> 
     <ellipsoidalHead> 
     <standardComponentData> 
      <identifier>Ellipsoidal Head #2</identifier> 
      <idNumber>2222</idNumber> 
      ... 
     </standardComponentData> 
     </ellipsoidalHead> 
    </topClosure> 
    </closure1> 
    <shell> 
    <cylinder> 
     <standardComponentData> 
     <identifier>Cylinder #1</identifier> 
     <idNumber>3333</idNumber> 
     ... 
     </standardComponentData> 
     .... 
    </cylinder> 
    <cylinder> 
     <standardComponentData> 
     <identifier>Cylinder #2</identifier> 
     <idNumber>4444</idNumber> 
     ... 
     </standardComponentData> 
     .... 
    </cylinder> 
    <cylinder> 
     <standardComponentData> 
     <identifier>Cylinder #3</identifier> 
     <idNumber>5555</idNumber> 
     ... 
     </standardComponentData> 
     .... 
    </cylinder> 
    <flange> 
     <standardComponentData> 
     <identifier>Top Head Flange #1</identifier> 
     <idNumber>6666</idNumber> 
     <attachedToidNumber>1111</attachedToidNumber> 
     ... 
     </standardComponentData> 
    </flange> 
    </shell> 
<pressureVessel> 

我在一些JavaScript被解析这个XML,和我有法兰元件作为所谓的bomNode变量。我需要做的是找到<idNumber>值与<flange>元素中的>attachedToidNumber>匹配的元素(在这种情况下,Ellipsoidal Head#1)。境内有<pressureVessel>其他多种元素,所以我需要做的是

  1. 查找以closure开头的元素(例如closure1,closure2等)。
  2. 在该元素中,找到一个<standardComponentData>,然后<idNumber>值与<attachedToidNumber>(我已存储在该变量中)的子元素。
  3. 获取该元素,以便我可以从中获取其他数据。

那么最有效的方法是什么?还有<pressureVessel>下的其他元素,所以我不想解析所有这些,如果我不必。

我的想法是做类似的东西

var elName = 'closure'; 
bomNode.parent().parent().find().has(elName).each(function(index() { 
    // Do something here 
}) 

,但我不知道在哪里可以从这里走,否则我连走上了正轨。

回答

0

您可以使用.filter()得到<idNumber>元素相匹配,其中.textContent等于<attachedToIdNumber>.textContent

$(xml).find("standardComponentData idNumber").filter(function(i, el) { 
    return $(el).parents().filter(function(i, el) { 
      return /closure/i.test(el.tagName) }).is("*") 
     && el.textContent === xml.find("attachedToidNumber").text() 
}) 
0

我在花了一枪根据我最好的你的使用情况的了解,并稍微更完整(但仍然猜测它)XML文件。

  1. 我制作了一个以closure开头的所有可用节点的数组。
  2. 从那里,用任何包含<standardComponentData>节点的元素填充另一个数组(称为attachableComponents)。
  3. 然后,这是一个创建一个功能,找到任何这些元素的问题。
  4. <flang><attachedToidNumber>的值传递给该函数,以便从该attachableComponents数组中抽取任何匹配的节点。

例JS滨呈现出来供视觉参考:

http://jsbin.com/hovovel/1/edit?html,js,output