如何显示XML标签中的文本?

时间:2013-09-16 07:55:11

标签: javascript jquery xml get

我有一个页面应该根据访问者的位置显示公司/公司。我使用插件来确定访问者的位置。公司列表存储在XML文件中,具有以下设置:

<?xml version="1.0" encoding="utf-8"?>
<Events>
  <EventItem>
    <Country>Abu Dhabi</Country>
    <Company>Trizac Abu Dhabi</Company>
    <Address>P.O. Box 4434 Abu Dhabi U.A.E.</Address>
    <Email Link="ahmad.nabulsi@trizac.ae"><![CDATA[ahmad.nabulsi@trizac.ae]]></Email>
    <Web Link=""><![CDATA[]]></Web>
    <Phone Link="tel:971 2 633 0552"><![CDATA[Phone:971 2 633 0552]]></Phone>
    <Fax Link="tel:971 2 633 0557"><![CDATA[Fax:971 2 633 0557]]></Fax>
  </EventItem>
</Events>

我使用以下代码显示数据(我先将它们放在警报中)

$.get(strXML, function(d){
                alert("Start search in : " + strXML + " for " + location.countryName); 
                $(d).find("Country:contains('Hong Kong')").each(function(){
                    var $lbp = $(this);
                    alert ($lbp.find("Company").text() + " hello " + $lbp.find("Address").text())
                }); //end of $(d).find
            }); //end of $.get

我首先硬编码location.countryName(在这种情况下,“香港”,因为我的定位器将国家/地区名称放在所有大写字母中,而XML中的数据是骆驼大写的(我仍然试图找出如何更改)在我的XML中,在香港有一家公司,代码可以看到。但是当我尝试在和标签中显示文本时,它只显示任何内容。

这就是为什么我在那里放置一个“你好”,只是为了看看警报代码是否至少有效。它是,但它没有为公司和地址显示任何内容:(

我也试过“日本”,它有四家公司,我在这个过程中收到四个警报,但我似乎无法从XML标签中显示数据:(非常感谢帮助:)我很新对于这个jQuery / XML组合,所以请耐心等待:(

1 个答案:

答案 0 :(得分:1)

问题是因为您已经完成了find()获取<Country />标记,然后您再次查看该国家/地区的内容,而不是那里。相反,你需要上升一个级别。试试这个:

$.get(strXML, function(d){
    alert("Start search in : " + strXML + " for " + location.countryName); 
    $(d).find("Country:contains('Hong Kong')").each(function(){
        var $lbp = $(this).closest('EventItem'); // Note the parent is selected here
        alert ($lbp.find("Company").text() + " hello " + $lbp.find("Address").text())
    });
});