IBM Cast Iron中使用XSLT移除XML标签内重复XML声明
I’ve run into similar headaches with malformed XML from integration tools before—those stray XML declarations nested inside tags break validity instantly. Here’s a reliable XSLT solution to clean up your badXml.xml file:
Sample Input (badXml.xml)
<?xml version="1.0" encoding="UTF-8"?> <Root> <FilteredData> <?xml version="1.0"?> <Record>ID: 123</Record> </FilteredData> <AnotherEntry> <?xml version="1.0" encoding="UTF-8"?> <Details>Sample content</Details> </AnotherEntry> </Root>
Expected Output
<?xml version="1.0" encoding="UTF-8"?> <Root> <FilteredData> <Record>ID: 123</Record> </FilteredData> <AnotherEntry> <Details>Sample content</Details> </AnotherEntry> </Root>
XSLT Solution
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!-- Copy all elements and their attributes to preserve structure --> <xsl:template match="*"> <xsl:copy> <xsl:copy-of select="@*"/> <xsl:apply-templates/> </xsl:copy> </xsl:template> <!-- Keep regular text content unchanged --> <xsl:template match="text()"> <xsl:copy/> </xsl:template> <!-- Explicitly ignore all XML declaration processing instructions --> <xsl:template match="processing-instruction('xml')"/> <!-- Optional: Preserve other processing instructions (like <?xml-stylesheet?>) --> <xsl:template match="processing-instruction()"> <xsl:copy/> </xsl:template> </xsl:stylesheet>
How This Works
- The first template ensures your core XML structure (elements and attributes) stays exactly as-is, so you don’t lose any valid data.
- The text node template keeps all regular content intact.
- The critical line is the template matching
processing-instruction('xml')—this targets and discards any<?xml ...?>declarations, no matter where they’re nested in the document. - The optional last template preserves other processing instructions if you have them (you can remove this if you don’t need to keep non-XML-declaration PIs).
Applying in IBM Cast Iron
Right after your Filter Activity, add an XSLT Transformation Activity to your workflow. Configure it to use the XSLT above, pointing to the badXml.xml output from the filter. This will automatically generate a cleaned-up, valid XML file ready for downstream processing.
Test this with your actual file to confirm all stray declarations are removed—edge cases like declarations with different encodings are still handled by this logic.
内容的提问来源于stack exchange,提问作者sandeep kairamkonda

