javascript - 使用 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”)。请帮忙。
解决方案
对于 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);
}
推荐阅读
- python - 当我用 plotly 着色时,为什么我的箱形图变窄了?
- c# - 如何将特定枚举的女巫值传递给方法
- string - 我需要使用 powershell 脚本的 AssemblyInfo.cs 的前 3 位版本号
- flutter - 如何在颤动中按下按钮时设置状态并调用另一个函数
- php - MySQL查询过滤结果
- javascript - 检查 X 数组的所有值是否都在 Y 中
- laravel - 查询中的错误数据,Laravel
- react-native - 状态更改后反应原生不重新渲染
- python - 使用 Pandas 规范化 JSON 将路径附加到列
- python - 带有日期时间的 Python os.rename 不断保存多个同名文件