Sunday 4 May 2014

Rename xml files using the value of an xml-node

Q&A

A customer wants to monitor a directory for new XML files and move/rename those files to a different directory. The files should be renamed to the value of an xml-node inside the xml file.

For example, the file 123.xml, which has the following contents

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<data-set xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 <Title>
  <PRMap>I_32c_T_A</PRMap>
  <IMP>HH</IMP>
  <Pszx>683</Pszx>
  <Pszy>560</Pszy>
  <PGszx>27.305</PGszx>
......

should be renamed to the value of the <PRMap> node, the 123.xml file will be renamed to I_32c_T_A.xml.

Solution

WatchDirectory does not directly support reading xml values, but we wrote a little helper program (GetFromXML.exe) to make this possible. The idea is to use the "Copy Files" task with the Dynamic Naming option.

One of the dynamic name tags allows you to call a batch script to determine (part of) the final name to use. This batch script can then read the xml file (using GetFromXML.exe) to extract the correct name to use.
Download GetFromXML here.

This is the batch script (GetFromXML.bat):

SET GET=C:\Bin\GetFromXml.exe
  
"%GET%" "%WD_FILE%" Title^|PRMap^|* > "%WD_FILTERRESULT%"
if %errorlevel% neq 0 (
  DEL "%WD_FILTERRESULT%"
  echo Error xml lookup in file fails > "%WD_FILTERRESULT%"
)

The script should be saved as C:\Program Files (x86)\WatchDirectory\Resolvers\GetFromXML.bat and now the customer can use the following "Dynamic Name" as the target for this copy files task:

C:\Target\{code{GetFromXml.bat,}}.xml

3 comments:

Unknown said...

if you wanted to get the name from a seperate XML file would that be possible... I would like to rename a jpg file when moving it to a new location and could copy an XML file to the same location with the details of the name I require.

Gert said...
This comment has been removed by the author.
Gert said...

Yes, that should be possible as well.

Can you email me a few example files (zip them up) and tell me exactly how they should be named and copied?

Please use full paths in your description (C:\MonitoredDir\SomeSubdir\filename.xml).

You can email me here:
gert at gdpsoftware dot com.

Post a Comment