web stats
Mirth Community - View Single Post - Mirth Tools: User defined functions
View Single Post
  #20  
Old 02-06-2013, 10:09 AM
narupley's Avatar
narupley narupley is online now
Mirth Employee
 
Join Date: Oct 2010
Posts: 7,126
narupley is on a distinguished road
Default Replace in All Descendant XML Nodes

Quote:
UPDATE: I've created a public GitHub repository to track these example channels, code templates, scripts, or whatever else!

https://github.com/nextgenhealthcare/connect-examples

To start with I only added the ones I wrote, because I didn't want to presume and add code from others without their explicit permission. Pull requests welcome!
replaceAllInXML: Recursively iterates through all descendant nodes of an E4X XML object and makes a string replacement.

This is useful if you want to make a global replacement in your message but only want to do it for a specific connector. Obviously you can do this in a preprocessor, but if you only want it to happen for a single destination, this function will allow you do to that easily.

Parameters:
  • parent: The node to recursively iterate through.
  • regexp: The regular expression to test against at each leaf (text) node. This should be a RegExp object, like "new RegExp('foo','g')" or "/foo/g".
  • replacement: The string with which to replace.

Examples:
  • Replace all single quotes (') with two single quotes (''), e.g. to prepare for inserting into a database:
    Code:
    replaceAllInXML(msg,/'/g,"''");
  • If any dates occur in a PID or OBR segment that do not have the hour/minute/second defined (i.e. it's only yyyyMMdd, like "20130206"), then add on the HHmmss ("000000"). This might be used to send to a system that requires those date fields to be in the full yyyyMMddHHmmss format.
    Code:
    for each (seg in msg.*.(function(){return/PID|OBR/.test((new XML(this)).name())}()))
    	replaceAllInXML(seg,/(?:19|20)\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])(?!\d)/g,'$&000000');

The code:

Code:
function replaceAllInXML(parent,regexp,replacement) {
	for each (child in parent.children())
		if (child.hasComplexContent())
			replaceAllInXML(child,regexp,replacement);
		else
			parent.children()[child.childIndex()] = child.toString().replace(regexp,replacement);
}
Attached Files
File Type: xml replaceAllInXML.xml (641 Bytes, 215 views)
__________________
Step 1: JAVA CACHE...DID YOU CLEAR ...wait, ding dong the witch is dead?

Nicholas Rupley
Work: 949-237-6069
Always include what Mirth Connect version you're working with. Also include (if applicable) the code you're using and full stacktraces for errors (use CODE tags). Posting your entire channel is helpful as well; make sure to scrub any PHI/passwords first.


- How do I foo?
- You just bar.

Last edited by narupley; 06-08-2018 at 11:35 AM.
Reply With Quote