如何从XML文件中提取<item>元素的name属性并填充列表?
Hey there! Let's figure out how to extract those name attributes from your XML file. Here's a practical solution that builds on your existing XMLHttpRequest code:
Extracting
name Attributes from XML <item> Elements Below is a complete, working example to load your XML and pull out the exact values you need:
Full JavaScript Implementation
// Initialize the request var request = new XMLHttpRequest(); // Replace 'your-xml-file.xml' with the actual path to your XML file request.open('GET', 'your-xml-file.xml', true); request.onload = function() { // Check if the request succeeded if (this.status >= 200 && this.status < 400) { // Parse the XML response into a document object var xmlDoc = this.responseXML; // Grab all <item> elements from the XML var itemElements = xmlDoc.getElementsByTagName('item'); // Array to store our extracted names var nameList = []; // Loop through each <item> and extract the 'name' attribute for (let i = 0; i < itemElements.length; i++) { var itemName = itemElements[i].getAttribute('name'); nameList.push(itemName); } // Format the result as you requested var formattedResult = nameList.join('、'); console.log(formattedResult); // Output: Gasp for surprise、Giggle、Say hello } else { console.error('Failed to load XML file: Server returned an error'); } }; // Handle request errors request.onerror = function() { console.error('Request failed: Could not connect to the server'); }; // Send the request request.send();
How This Works
- XMLHttpRequest: We finish setting up the request to load your XML file, then use
responseXMLto get a parsed XML document (no manual string parsing needed!). - Element Selection:
getElementsByTagName('item')fetches all<item>nodes from the XML. - Attribute Extraction: For each
<item>element,getAttribute('name')pulls out the value of thenameattribute, which we add to ournameListarray. - Formatting: Finally,
join('、')combines the array into the exact string format you want.
Alternative: If You Have XML as a String
If your XML is already stored as a string (instead of loading from a file), use DOMParser for a more concise approach:
var xmlString = `<?xml version="1.0"?> <sendSound enable="true" autoPlay="true"> <item name="Gasp for surprise" src="flashsound/gasp.mp3"></item> <item name="Giggle" src="flashsound/hehe.mp3"></item> <item name="Say hello" src="flashsound/hello.mp3"></item> </sendSound>`; var parser = new DOMParser(); var xmlDoc = parser.parseFromString(xmlString, 'text/xml'); // Use modern array methods to collect names var nameList = Array.from(xmlDoc.getElementsByTagName('item')) .map(item => item.getAttribute('name')); console.log(nameList.join('、'));
内容的提问来源于stack exchange,提问作者Cain Nuke
相关产品推荐
相关产品推荐

