Java, Software Development

Java, XSLT, and XML with Namespaces

When a XML uses namespaces, they need to be declared and used in the .xsl file so that the javax.xml.transform.Transformer knows how to deal with various elements in the XML. This post demonstrates how to deal with namespaces when performing transformation from or on XMLs.

Requirements

Stuff used in this post.

  • Java 8 (JDK)
  • Eclipse Mars.2 Release (4.5.2)
  • Windows 10
  • XSLT 1.0

Purpose

So we want to:

  1. Modify elements that use prefixes from different namespaces
  2. Conditional modify attributes and retaining their prefixes, if any.
  3. Conditional modify elements based on their values (i.e., from text())

We’ll use files

  • input.xml
    • The file whose content is to be modified and written out to output.xml
  • transformation.xsl
    • Contains XSL expressions to modify certain data
  • output.xml
    • The output file

Input XML

Our Java Codes

XSL

The Transformation

Change TITLE string value to upper-case string value

The expression below replaces all TITLE string value to upper-case string value. “Empire Burlesque” is changed to “EMPIRE BURLESQUE”.

Change PRICE’s type attribute value conditionally

If type is “WholeSalePrice”, replace it with “whole-sale-price” and retaining the attribute’s prefix.

If type is “RetailSalePrice”, replace it with “retail-sale-price” and retaining the attributes’ prefix.

Change only “Bob Dylan” to “BOB DYLAN”

Download the Codes

https://github.com/Turreta/Java-XSLT-and-XML-with-Namespaces

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like