Remove Specified XML Attributes

You might want to remove specific attributes from within an XML tag that are known to contain sensitive data. The DataWeave example defines a function in the DataWeave header that removes a specific XML attribute from the passed element and its children. Before you begin, note that 2.x versions of DataWeave are used by Mule 4 apps. For DataWeave in Mule 3 apps, refer to DataWeave version 1.2 examples. For other DataWeave versions, you can use the version selector in the DataWeave table of contents.

This example uses:

  • mapObject to go through each element.

  • @ to refer to the attributes in an XML element.

  • if and else to conditionally only list XML attributes when they are present, and also to only recursively call the function when a child element is an object.

  • is to check if each child is of type Object .

  • - to remove an element from the list of XML attributes.

  • inlineCloseOn="empty" on the output directive, so that the output XML displays self-closing tags when there are no values.

If the parent users object or child user objects within the input contain an attribute with the key password, removeAttributes removes that attribute from the object.

DataWeave Script:
%dw 2.0
output application/xml inlineCloseOn="empty"
var removeAttribute = (element,attrName) ->
  element mapObject (value, key) -> {
    // Pass the name of the key of the input object,
    // for example, whether the key is "users" or "user",
    // and use @() to remap the XML attributes.
    (key) @(
          // If the element contains attributes (key.@?),
          // remove any attribute that has the provided key,
          // "password".
          if (key.@?)
            (key.@ - attrName)
          // Otherwise, do nothing.
          else {}
    ) :
    // If the value of the input object contains one or
    // more objects, apply removeAttribute to remove any
    // attribute with the key "password" from those objects.
    if (value is Object)
      removeAttribute(value, attrName)
    // Otherwise, return the value of the input object.
    else value
removeAttribute(payload, "password")
Input XML Payload:
  <user username="Julian" password="1234"/>
  <user username="Mariano" password="4321"/>
Output XML:
<?xml version='1.0' encoding='US-ASCII'?>
  <user username="Julian"/>
  <user username="Mariano"/>

Was this article helpful?

💙 Thanks for your feedback!

Edit on GitHub
Submit your feedback!
Share your thoughts to help us build the best documentation experience for you!
Take our latest survey!