如何从 XML 文件创建 Javascript 数组或对象?

问题描述 投票:0回答:1

首先我必须声明,尽管我使用 html、php、MySQL 和一些 javascript 创建了一个方便的网站,但我并不是编程方面的冠军。显然,JS 是我小时候几乎使用的语言!

我在 xml 文件中有一组数据,其结构如下(抱歉字符编码不好):

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> 
<markers> 
 <marker lat="50.84310" lng="4.39330" name="7.7cm Sockel Flak 16 RheinMetall" category="FlakKanonen" nation="Allemagne" typecanon="Artillerie de DCA" lieu="Bruxelles - Musée Royal de l'Armée" pays="Belgique" url="../AfficheCanonGET.php?IdCanonAffiche=170" /> 
 <marker lat="43.13810" lng="-80.26170" name="15cm sFH 13 L/14" category="SchwerenKanonen" nation="Allemagne" typecanon="Artillerie lourde" lieu="Brantford (ON) - Monument" pays="Canada" url="../AfficheCanonGET.php?IdCanonAffiche=256" />  
 <marker lat="61.00500" lng="24.45780" name="10cm K 14" category="LeichtKanonen" nation="Allemagne" typecanon="Artillerie légère" lieu="Hameenlinna - Finnish Artillery Museum" pays="Finlande" url="../AfficheCanonGET.php?IdCanonAffiche=317" />  
 <marker lat="45.88740" lng="11.04740" name="7cm M 99 GebK" category="GebirgsKanonen" nation="Autriche-Hongrie" typecanon="Artillerie de montagne" lieu="Rovereto - Museo Storico Italiano della Guerra" pays="Italie" url="../AfficheCanonGET.php?IdCanonAffiche=733" /><marker lat="-35.21550" lng="149.14510" name="13cm K 09 L/35" category="SchwerenKanonen" nation="Allemagne" typecanon="Artillerie lourde" lieu=" Mitchell, ACT - AWM reserve" pays="Australie" url="../AfficheCanonGET.php?IdCanonAffiche=1519" /> 
</markers>

此 xml 文件在 JavaScript 代码中使用,用于在 GoogleMap 上放置标记。好吧,它曾经是这样,因为自从 GoogleMap 迁移到 APIV3 以来,代码不再工作,而且我使用的 xml 导入功能没有可移植性。

我设法用新的 API v3 语言重写地图代码,但我陷入了对你来说可能非常简单的困境:尽管阅读了数十个类似的线程,但我无法调整 JavaScript 中的代码来传输这些 xml 文件数据在 JavaScript 数组中

这就是我希望创造的东西:

marqueurCanonTest4[0] = {
  latitudeCanon: "-34.94570",
  longitudeCanon: "138.58050",
  nomCanon: "7.7cm FK 16",
  categorieCanon: "LeichtKanonen",
  nationCanon: "Allemagne",
  typeCanon: "Artillerie légère",
  lieuCanon: "Adelaide, SA  - Keswick Barracks, Army Museum of South Australia",
  paysCanon: "Australie",
  url: "../AfficheCanonGET.php?IdCanonAffiche=1"
};
marqueurCanonTest4[1] = {
  latitudeCanon: "-36.14640",
  longitudeCanon: "146.91680",
  nomCanon: "7.7cm FK 16",
  categorieCanon: "LeichtKanonen",
  nationCanon: "Turquie",
  typeCanon: "Artillerie légère",
  lieuCanon: "Bandiana, VIC - Army Museum",
  paysCanon: "Australie",
  url: "../AfficheCanonGET.php?IdCanonAffiche=2"
};

等等...

我尝试过使用

XMLHttpRequest
,但可能不正确。

实现我的目标的方法是什么?

javascript arrays xml data-structures domparser
1个回答
0
投票

如果我正确理解您的问题,您需要从提供的 XML 文件在 JavaScript 中创建一个标记数组。

您需要解析 XML 内容并提取必要的数据。您可以使用浏览器的 DOMParser 将 XML 字符串转换为 DOM 对象,然后遍历节点以提取标记信息来实现此目的。

以下是如何执行此操作的示例:

// Fetch the XML file
fetch('path/to/your/file.xml')
  .then(response => {
    // Check if the response is successful
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    // Parse the response as text
    return response.text();
  })
  .then(xmlString => {
    // Parse the XML string
    const parser = new DOMParser();
    const xmlDoc = parser.parseFromString(xmlString, 'text/xml');

    // Extract marker information
    const markers = Array.from(xmlDoc.getElementsByTagName('marker')).map(marker => ({
      lat: marker.getAttribute('lat'),
      lng: marker.getAttribute('lng'),
      name: marker.getAttribute('name'),
      category: marker.getAttribute('category'),
      nation: marker.getAttribute('nation'),
      typecanon: marker.getAttribute('typecanon'),
      lieu: marker.getAttribute('lieu'),
      pays: marker.getAttribute('pays'),
      url: marker.getAttribute('url'),
    }));

    // Output the markers array
    console.log(markers);
    
    // Use the 'markers' array in further processing here or within this scope
  })
  .catch(error => {
    console.error('There was a problem fetching the file:', error);
  });

© www.soinside.com 2019 - 2024. All rights reserved.