Tuesday, January 12, 2016

XML file changing using regex by Java and apache commons - Made Easy

We need to download commons io 2.4 for the related java code.
Commons IO 2.4 (requires JDK 1.6+)

Commons IO 2.4 is the latest version and requires a minimum of JDK 1.6 - Download now!

XML File: DataInputFile.xml

<? Xml version = "1.0" encoding = "UTF-8"?>
<LayoutDef xmlns: intramart = "http://intramart/maskat/1.0.0" xmlns: dojo = "http://maskat.sourceforge.jp/widget/dojo/1.0.0">
  <Layout name = "dataMapper">
  </ Layout>
</ LayoutDef>

Java File: ReplacerUsingRegex.java

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.IOUtils;

public class ReplacerUsingRegex {

/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
   // Input and Output File
File xmlFile = new File("C:/data/ DataInputFile.xml");
File newXmlFile = new File("C:/data/DataOutputFile.xml");

// Pattern data and Replacement data Map
HashMap<String, String> hmap = new HashMap<String, String>();
hmap.put("(.*) ([=+*&:/]) (.*)", "$1$2$3");
hmap.put(" Xml", "xml");
hmap.put("<Layout", "<layout");
hmap.put("</ Layout", "</layout");
hmap.put("xmlns: ", "xmlns:");

// Apache Commons method for replacement
String content = IOUtils.toString(new FileInputStream(xmlFile), "UTF-8");
for (Map.Entry m : hmap.entrySet()) {
content = content.replaceAll(m.getKey().toString(), m.getValue().toString());
}
IOUtils.write(content, new FileOutputStream(newXmlFile), "UTF-8");
System.out.println("Finished Successfully!!!");
}
}

No comments:

Post a Comment