如何使用jQuery'find'避免xml中具有相同标记的多个节点与命名空间?

时间:2010-11-29 12:42:13

标签: javascript jquery xml wcf xml-namespaces

我有以下XML

<ProjectResponse xmlns="Services.Messages" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">    
  <Projects xmlns:a="Services.DTO">
    <a:Project>
      <a:ID>113</a:ID>
      <a:Name>Test project</a:Name>
      <a:Documents>
        <a:ProjectDocument>
          <a:FileName>DS.docx</a:FileName>
          <a:ID>65</a:ID>
          <a:ProjectID>113</a:ProjectID>
        </a:ProjectDocument>        
      </a:Documents>
    </a:Project>
  </Projects>
</ProjectResponse>

当我在'each'函数中执行$(this).find('[nodeName = a:ID]')时,我得到2个ID,一个来自Project,另一个来自Document。

$(projectsXml).find('Projects').children().each(function() {
            var projectId = $(this).find('[nodeName=a:ID]').text();

问题是如何才能获得项目ID,而不是文档ID和可能出现的其他ID?

1 个答案:

答案 0 :(得分:2)

也可以使用.children()代替.find(),因此它只会查找直接子项,如下所示:

$(projectsXml).find('Projects').children().each(function() {
  var projectId = $(this).children('[nodeName=a:ID]').text();
});