简体   繁体   English

无法使用jQuery获取XML元素文本值

[英]Can't get xml element text value using jquery

I have a an ajax call that returns an xml response. 我有一个ajax调用,它返回一个xml响应。 I want to get the value of one of the elements in this response , ie 'Some Name'. 我想获取此响应中元素之一的值,即“某些名称”。 The problem is that there are 5 or 6 of these tags in the response. 问题是响应中有5或6个这些标签。 Is there a way to get the value of just the first one? 有没有办法获得第一个的价值? It's always the first one I will want to use. 它始终是我要使用的第一个。 Here is some of the code: 这是一些代码:

var xmlData = '<userId internalId="Some Number"xmlns:platformCore="urn:core_2013_1.platform.webservices.netsuite.com"><platformCore:name>Some Name</platformCore:name></userId>';
var $xml = $(xmlData);
var $user = $xml.find("platformCore:name").text();
alert($user);

I also have a js fiddle here: http://jsfiddle.net/8FqRd/5/ 我在这里也有一个js小提琴: http : //jsfiddle.net/8FqRd/5/

EDIT: FIX BELOW: 编辑:在下面修复:

My ajax response was already in xml form, so no need to parse. 我的ajax响应已经是xml格式,因此无需解析。 This line worked for me: 这行对我有用:

var user = $(xmlResponse).find("userId").find("name").text();

The main jQuery function doesn't parse XML correctly: it treats it as HTML, with variable results. jQuery的主要功能无法正确解析XML:它将其视为HTML,结果可变。 Use $.parseXML() instead. 使用$.parseXML()代替。

I'm not sure how jQuery deals with XML, particularly namespaces. 我不确定jQuery如何处理XML,特别是名称空间。 I would guess not at all. 我猜完全没有。 However, searching for elements by local name rather than fully qualified name seems to work. 但是,按本地名称而不是完全限定的名称搜索元素似乎可行。

Demo: http://jsfiddle.net/timdown/8FqRd/6/ 演示: http//jsfiddle.net/timdown/8FqRd/6/

var xmlData = '<userId internalId="Some Number"xmlns:platformCore="urn:core_2013_1.platform.webservices.netsuite.com"><platformCore:name>Some Name</platformCore:name></userId>';
var $xml = $( $.parseXML(xmlData) );
var $user = $xml.find("name").text();
alert($user);

As Tim pointed out you need to use $.parseXML(xmlData) 正如Tim所指出的,您需要使用$.parseXML(xmlData)

However as your xml tag has a : in it, you will have to escape it. 但是,由于您的xml标记中包含: ,因此您必须对其进行转义。

var xmlData = '<userId internalId="Some Number" xmlns:platformCore="urn:core_2013_1.platform.webservices.netsuite.com"><platformCore:name>Some Name</platformCore:name></userId>';
var xml = $.parseXML(xmlData);
var $xml = $(xml);
var $user = $xml.find("platformCore\\:name").text(); // you need to escape the : 
alert($user);

Check http://jsfiddle.net/8FqRd/7/ for a demo 查看http://jsfiddle.net/8FqRd/7/进行演示

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

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