我有如下的xml数据,我想检索所有电台名称,ID和流派。如何使用javascript做到这一点?
<somelist>
<datatune base="/sbin/somelist.pls" base-m3u="/sbin/tunein-station.m3u" base-xspf="/sbin/tunein-station.xspf"/>
<list name="COOLfahrenheit 93 - (1)" mt="audio/mpeg" id="1392941" br="64" genre="Easy Listening" genre2="Pop" logo="http://i.radionomy.com/document/radios/3/32d2/32d25a06-b423-4d16-9541-7980a2669da3.png" ct="The TOYS - +I2+2'5HA%I'" lc="3220"/>
<list name="COOLfahrenheit 93 - (5)" mt="audio/mpeg" id="1453011" br="64" genre="Easy Listening" genre2="Pop" logo="http://i.radionomy.com/document/radios/f/f9a7/f9a74fd5-f1d4-41c1-9f8a-fcc62470bb31.png" ct="The TOYS - +I2+2'5HA%I'" lc="2348"/>
<list name="COOLfahrenheit 93 - (4)" mt="audio/aacp" id="1460193" br="64" genre="Easy Listening" genre2="Pop" logo="http://i.radionomy.com/document/radios/f/f6d5/f6d5d27f-397e-4b67-8564-8f043b2b5336.png" ct="The TOYS - +I2+2'5HA%I'" lc="1915"/>
</somelist>
谢谢,
答案 0 :(得分:0)
试试这个:
var xmlstring = `<somelist><datatune base="/sbin/somelist.pls" base-m3u="/sbin/tunein-station.m3u" base-xspf="/sbin/tunein-station.xspf"/><list name="COOLfahrenheit 93 - (1)" mt="audio/mpeg" id="1392941" br="64" genre="Easy Listening" genre2="Pop" logo="http://i.radionomy.com/document/radios/3/32d2/32d25a06-b423-4d16-9541-7980a2669da3.png" ct="The TOYS - +I2+2'5HA%I'" lc="3220"/><list name="COOLfahrenheit 93 - (5)" mt="audio/mpeg" id="1453011" br="64" genre="Easy Listening" genre2="Pop" logo="http://i.radionomy.com/document/radios/f/f9a7/f9a74fd5-f1d4-41c1-9f8a-fcc62470bb31.png" ct="The TOYS - +I2+2'5HA%I'" lc="2348"/><list name="COOLfahrenheit 93 - (4)" mt="audio/aacp" id="1460193" br="64" genre="Easy Listening" genre2="Pop" logo="http://i.radionomy.com/document/radios/f/f6d5/f6d5d27f-397e-4b67-8564-8f043b2b5336.png" ct="The TOYS - +I2+2'5HA%I'" lc="1915"/></somelist>`
然后根据Here,您可以:
var oParser = new DOMParser();
var oDOM = oParser.parseFromString(xmlstring, "text/xml");
var listHtmlCollection = oDOM.getElementsByTagName("list");
var listArr = Array.prototype.slice.call( listHtmlCollection ); //see: stackoverflow.com/questions/222841/most-efficient-way-to-convert-an-htmlcollection-to-an-array
var stationNames = listArr.map(le => le.getAttribute("name"));
console.log(stationNames);
应该给出:
Array [ "COOLfahrenheit 93 - (1)", "COOLfahrenheit 93 - (5)", "COOLfahrenheit 93 - (4)" ]
您可以对其他属性(id,gnere等)使用相同的方法。