XSLT 1.0技术问询:使用属性数量不等但同名的元素生成HTML表格
To solve this problem, we need to create an HTML table where headers are all unique attribute names from your XML elements, and each row corresponds to an element's attribute values—with empty cells for any missing attributes. Here's a step-by-step approach with code examples in two common languages:
Step 1: Extract All Unique Attributes
First, we need to gather every distinct attribute name across all target elements (in your case, <child> elements). This ensures our table includes all possible headers, even if some elements don't have certain attributes.
Step 2: Build the HTML Table
Once we have the full list of attributes, we can construct the table:
- Create a header row using the sorted unique attributes (for consistency).
- For each element, create a row where we fill in values for existing attributes and empty strings for missing ones.
Example in Python
We'll use Python's built-in xml.etree.ElementTree module for XML parsing:
import xml.etree.ElementTree as ET # Parse your XML file (or string) tree = ET.parse('your_xml_file.xml') root = tree.getroot() # Get all <child> elements child_elements = root.findall('.//child') # Collect all unique attribute names all_attributes = set() for child in child_elements: all_attributes.update(child.attrib.keys()) # Sort attributes to keep headers consistent (optional but recommended) sorted_attributes = sorted(all_attributes) # Generate HTML table html_table = '<table>\n' # Add header row html_table += ' <tr>\n' for attr in sorted_attributes: html_table += f' <th>{attr}</th>\n' html_table += ' </tr>\n' # Add data rows for child in child_elements: html_table += ' <tr>\n' for attr in sorted_attributes: # Get attribute value or empty string if missing attr_value = child.attrib.get(attr, '') html_table += f' <td>{attr_value}</td>\n' html_table += ' </tr>\n' html_table += '</table>' # Print or save the result print(html_table)
Example in JavaScript
If you're working in a browser or Node.js environment, here's how to do it with the DOMParser:
// Your XML string (or load from a file) const xmlContent = `<root> <oelement attr="abc"> <ielement attr="101"> <child attr1="a" attr2="b" attr3="c" attr4="d"/> <child attr1="x" attr3="z"/> <child attr2="y" attr4="w"/> </ielement> </oelement> </root>`; const parser = new DOMParser(); const xmlDoc = parser.parseFromString(xmlContent, "text/xml"); const childElements = xmlDoc.querySelectorAll('child'); // Collect all unique attributes const allAttributes = new Set(); childElements.forEach(child => { Array.from(child.attributes).forEach(attr => allAttributes.add(attr.name)); }); const sortedAttributes = Array.from(allAttributes).sort(); // Build the HTML table let htmlTable = '<table>\n <tr>\n'; sortedAttributes.forEach(attr => { htmlTable += ` <th>${attr}</th>\n`; }); htmlTable += ' </tr>\n'; childElements.forEach(child => { htmlTable += ' <tr>\n'; sortedAttributes.forEach(attr => { const attrValue = child.getAttribute(attr) || ''; htmlTable += ` <td>${attrValue}</td>\n`; }); htmlTable += ' </tr>\n'; }); htmlTable += '</table>'; console.log(htmlTable);
Key Notes
- Using a
set(Python) orSet(JavaScript) ensures we only keep unique attribute names. - Sorting the attributes guarantees the header order stays consistent every time you run the code.
- Using
attrib.get()(Python) orgetAttribute()with a fallback to empty string ensures missing attributes result in blank<td>cells.
内容的提问来源于stack exchange,提问作者Aniket V

