替换& # 39;,& # 39;& # 39;, amp;& # 39;从XML到javascript

replace ' & ' to ' & ' from xml in javascript

本文关键字:javascript XML amp 替换      更新时间:2023-09-26

我试图用javascript解析动态xml文件。但是<link>元素中的url包含了琥珀色符号(&)
。所以我必须创建一个函数来动态地替换符号' & '与' &amp; '。

你知道我该怎么做吗?

这是整个html文件

<html>
    <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <title>metar.gr</title>
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript" src="util.js"></script>
    <script src="js/libs/require.js" data-main="js/mobile"></script>
    <link rel="stylesheet" href="https://d10ajoocuyu32n.cloudfront.net/mobile/1.3.1/jquery.mobile-1.3.1.min.css"/>
    <link rel="stylesheet" href="fonts-and-colors.css" type="text/css" media="screen">
    <script type="text/javascript">
      var infowindow;
      var map;
      function initialize() {
        var myLatlng = new google.maps.LatLng(38.822590,24.653320);
        var myOptions = {
          zoom: 6,
          center: myLatlng,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
        downloadUrl("moredata.xml", function(doc) {
          var items = doc.documentElement.getElementsByTagName("item");
          for (var i = 0; i < items.length; i++) {
            var description = items[i].getElementsByTagName("description")[0].textContent;
            var temp        = items[i].getElementsByTagName("temp")[0].textContent;
            var title       = items[i].getElementsByTagName("title")[0].textContent;
            var link       = items[i].getElementsByTagName("link")[0].textContent;
            var windSpeed   = items[i].getElementsByTagName("windSpeed")[0].textContent;
            var dailyRain   = items[i].getElementsByTagName("dailyRain")[0].textContent;
            var latlng      = new google.maps.LatLng(parseFloat(items[i].getElementsByTagName("glat")[0].textContent),
                                                     parseFloat(items[i].getElementsByTagName("glon")[0].textContent));
            if ( temp <= "1 °C" ) {
              //alert(temp);
              var marker = createMarker( temp,latlng,cold );
              }
            if ( temp >= "38 °C" ) {
              //alert(temp);
              var marker2 = createMarker2( temp,latlng,hot );
              }
           }
         });
      }
      var cold  = 'weather_icons/pagetos2.png';
      var hot   = 'weather_icons/hot.png';
      function createMarker( temp,latlng,cold ) {
        var marker = new google.maps.Marker({
        position: latlng,
        map: map,
        icon: cold
        });
        google.maps.event.addListener(marker, "click", function() {
          if (infowindow) infowindow.close();
          infowindow = new google.maps.InfoWindow({
          content: temp
          });
          infowindow.open(map, marker);
        });
        return marker;
      }
      function createMarker2( temp,latlng,hot ) {
        var marker2 = new google.maps.Marker({
        position: latlng,
        map: map,
        icon: hot
        });
        google.maps.event.addListener(marker2, "click", function() {
          if (infowindow) infowindow.close();
          infowindow = new google.maps.InfoWindow({
          content: temp
          });
          infowindow.open(map, marker2);
        });
        return marker2;
      }
</script>
</head>
<body onload="initialize()">
    <div data-role="header" data-theme="b">
        <div align="center">
                     <img  onclick='doAction("showStoreLocatorMap()")' src="http://www.metar.gr/templates/metar/images/metar.gif"  alt="main logo" vspace="2"/>
        </div>
        <a href="main.html" data-role="button" data-inline="true">Home</a>
    </div>
    <div data-role="content">
            <div id="map_canvas" ></div>    
    </div>
        <div data-role="info_icons">
        <ul data-role="listview" id="icon_info" data-theme="c"> 
        <img src="weather_icons/pagetos2.png"/>  
        <h3 class="ui-li-heading">Cold</h3>  
        <p class="ui-li-desc">temprature < +4° C</p>
        </li> 
        <li>
        <img src="weather_icons/hot.png"/>  
        <h3 class="ui-li-heading">Hot</h3>  
        <p class="ui-li-desc">temprature > +38° C</p>
        </li>       
        </ul>
        </div>
    <div data-role="footer" data-theme="b">
        <h4>metar.gr mobile version</h4> 
    </div>
</body>
</html>

xml文件的示例

 <item>
      <description>Thesaloniki</description>
      <glat>40.422726139672626</glat>
      <glon>22.93392777442932</glon>
      <title>makedonia</title>
      <temp>60  °C</temp>
      <dailyRain>0 mm</dailyRain>
      <windSpeed>3.1 km/hr</windSpeed>
      <link>
         http://www.metar.gr/index.php?option=com_jumi&fileid=12&Itemid=73&station=1475
      </link>
  </item>
  <item>
      <description>Giannena</description>
      <glat>39.62209843837158</glat>
      <glon>20.89027225971222</glon>
      <title>ipiros</title>
      <temp>-16.9°C</temp>
      <dailyRain>0.0 mm</dailyRain>
      <windSpeed>10 km/hr</windSpeed>
      <link>
          http://www.metar.gr/index.php?option=com_jumi&fileid=12&Itemid=73&station=1227
      </link>
  </item>
  <item>
      <description>Athina</description>
      <glat>38.08469095792561</glat>
      <glon>23.680233657360077</glon>
      <title>sterea</title>
      <temp>45°C</temp>
      <dailyRain>0.0 mm</dailyRain>
      <windSpeed>97  km/hr</windSpeed>
      <link>
         http://www.metar.gr/index.php?option=com_jumi&fileid=12&Itemid=73&station=1009
      </link>
  </item>

util.js文件的一部分

function downloadUrl(url, callback) {
 var status = -1;
 var request = createXmlHttpRequest();
 if (!request) {
   return false;
 }
 request.onreadystatechange = function() {
   if (request.readyState == 4) {
     try {
       status = request.status;
     } catch (e) {
       // Usually indicates request timed out in FF.
     }
     if (status == 200) {
       callback(request.responseXML, request.status);
       request.onreadystatechange = function() {};
     }
   }
 }
 request.open('GET', url, true);
 try {
   request.send(null);
 } catch (e) {
   changeStatus(e);
 }
};

您向我们展示的"xml"不是格式良好的xml(也就是说,它根本不是xml)。需要XML解析器来拒绝格式错误的XML。正确的方法是找出是哪个流氓应用程序生成了这些损坏的数据,并从源头解决问题。一旦人们开始发送(并接受!)糟糕的XML,使用标准交换格式的好处就会很快消失。

如果你不能这样做,你需要写一个修复工具。因为您的数据不是XML,所以您不能使用XML工具完成这项工作;使用Perl之类的东西。具体细节取决于您希望XML中出现哪种类型的错误,例如,您是否只需要处理未转义的&号,或者还需要处理未声明的实体引用,如&nbsp;

如果你想知道这个函数是如何工作的,你已经在上面的评论中看到了:

return unsafe.replace(/&/g, "&amp;");

返回unsafe,在replace 之后,所有 (g全局修饰符)与"&amp;"匹配的正则表达式/&/(匹配文字&号)

我在stackoverflow中找到了一个类似问题的答案,我引用它。我必须将xml文件读取为String.replace
看一看!

您试图读取的文件不是有效的XML。没有一个自尊的XML解析器会接受它。

  I'm retrieving my XML dynamically from the web. What's the best way to replace all my escape  
characters after fetching the Document object?

你走错路了。正确的方法是通知负责创建该文件的人员该文件无效,并请求他们修复该文件。简单地编写hack来(尝试)修复损坏的XML不符合您(或其他人)的长期利益。

如果您决定忽略此建议,那么一种方法是将文件读入String,使用String。replaceAll(regex, replacement)使用合适的regex将这些虚假的"&"字符转换为适当的字符实体("&"),然后将固定的XML字符串提供给XML解析器。您需要仔细设计regex,这样它就不会破坏有效的字符实体,从而产生不必要的副作用。第二种方法是手工进行解析和替换,使用适当的启发式方法从格式良好的字符实体中区分虚假的"&"字符。

但是这些都花费了你的开发和测试时间,并且减慢了你的软件速度。更糟糕的是,由于您努力弥补错误的输入文件,您的代码可能会很脆弱,这是一个很大的风险。(猜猜谁会受到责备…)