如何使用jQuery选择具有唯一文本内容的XML节点? [英] How to use jQuery to select XML nodes with unique text content?

查看:47
本文介绍了如何使用jQuery选择具有唯一文本内容的XML节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从XML文档jQuery方式中提取一个唯一文本条目列表,并且正在进行攻击。

I'm attempting to pull a list of unique text entries from an XML document "the jQuery way" and am hitting a wall.

从这个XML:

<items>
  <item>
    <categories>
      <cat>Category 1</cat>
      <cat>Category 2</cat>
    </categories>
  </item>
  <item>
     <categories>
      <cat>Category 2</cat>
      <cat>Category 3</cat>
  </item>
 </items>

我想生成一个选择列表,如:

I'd like to generate a select list like:

<select>
 <option>Category 1</option>
 <option>Category 2</option>
 <option>Category 3</option>
</select>

到目前为止,我的所有尝试都产生了重复的类别2选项节点。我试图使用$ .unique()方法,但结果让我认为它只是比较节点名称而不是文本内容。这是我最新的hackery不起作用:

So far all of my attempts produce a duplicate "Category 2" option node. I attempted to make use of the $.unique() method, but the results make me think it's only comparing the node name, not the text content. Here is my latest hackery that does not work:

var filters = $("cat",xmldoc);
filters = $.unique(filters);
$(filters).each(function()
{
    $("select").append("<option>" + $(this).text() + "</option>");
});

我可以想到一些标准的javascript技巧来实现这一点,但我希望有一个很好的,优雅的jQuery方式拉这个。

I can think of a number of standard javascript tricks to make this happen, but am hoping there's a nice, elegant jQuery way to pull this off.

非常感谢任何提示或技巧。

Any tips or tricks would be greatly appreciated.

谢谢!

推荐答案

cat 元素不是重复的,因为它们具有相同的文本内容。它们仍然是具有各自不同身份的元素,因此唯一不会删除它们。

The cat elements are not duplicates just because they have the same text content. They're still elements with their own, different identity, and consequently unique will not remove them.

你' ll必须将文本内容读入数组,然后从Array-of-String中删除重复项。

You'll have to read the text contents into an array instead, and then remove duplicates from the Array-of-String.

不幸的是,你也不能使用<$ c之后在String-of-String上有$ c> unique ,因为它只支持DOM元素项。

Unfortunately, you also can't use unique afterwards on the Array-of-String, because it only supports DOM element items.

我只是做了一个骗局构建列表时删除:

I'd just do the dupe removal when building the list:

var cats= [];
$('cat', xmldoc).each(function() {
    var text= $(this).text();
    if ($.inArray(text, cats)===-1)
        cats.push(text);
});

然后将每个选项添加到选择中:

Then add each option to the select:

$.each(cats, function() {
    $('select').append($('<option>').attr('val', this).attr('text', this));
});

需要使用 attr 并且通过将整个元素作为HTML传递。当你从文本中创建HTML时,你必须HTML注释你注入HTML的任何文本字符串,否则你将有潜在的跨站点脚本安全漏洞。

The option text needs to be set using attr and not by passing in the whole element as HTML. When you make HTML from text, you have to HTML-escape any text strings you are injecting into the HTML, otherwise you'll have potential cross-site-scripting security holes.

这篇关于如何使用jQuery选择具有唯一文本内容的XML节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆