首页 > 解决方案 > 使用 scala 或 javascript 从 xml 获取元素名称列表

问题描述

我的 xml 文件如下所示

<?xml version="1.0" encoding="UTF-8"?>
<root>
<city>
<ID>1</ID>
<Name>Kabul</Name>
<CountryCode>AFG</CountryCode>
<District>Kabol</District>
<Population>1780000</Population>
</city>
<city>
<ID>2</ID>
<Name>Qandahar</Name>
<CountryCode>AFG</CountryCode>
<District>Qandahar</District>
<Population>237500</Population>
</city>
<city>
<ID>3</ID>
<Name>Herat</Name>
<CountryCode>AFG</CountryCode>
<District>Herat</District>
<Population>186800</Population>
</city>
</root>

我需要使用 scala 或 javascript 获取元素名称(“ID”、“Name”、“CountryCode”、“District”、“Population”)。请帮忙。

标签: javascriptscala

解决方案


对于 JavaScript,就像使用 DOM 中的元素一样。(但不要忘记解析 XML!)

var xml = '<?xml version="1.0" encoding="UTF-8"?><root><city><ID>1</ID><Name>Kabul</Name><CountryCode>AFG</CountryCode><District>Kabol</District><Population>1780000</Population></city><city><ID>2</ID><Name>Qandahar</Name><CountryCode>AFG</CountryCode><District>Qandahar</District><Population>237500</Population></city><city><ID>3</ID><Name>Herat</Name><CountryCode>AFG</CountryCode><District>Herat</District><Population>186800</Population></city></root>';

var parser = new DOMParser();
// Parse the xml
var parsedXML = parser.parseFromString(xml, 'text/xml');

// Now get the elements
var id = parsedXML.getElementsByTagName('ID');
var Name = parsedXML.getElementsByTagName('Name');
var countryCode = parsedXML.getElementsByTagName('CountryCode');
var district = parsedXML.getElementsByTagName('District');
var population = parsedXML.getElementsByTagName('Population');

// Get the tag names; because getElementsByTagName returns an array like HTMLCollection, we need to loop through the results like we would with an array
for (var i = 0; i < id.length; i++) {
  console.log(id[i].tagName + " " + Name[i].tagName+ " " + countryCode[i].tagName + " "+ district[i].tagName + " "+ population[i].tagName);
}


推荐阅读