Wednesday, January 6, 2016

XML file changing using regex by Java

XML File: file.xml

<?xml version="1.0" encoding="UTF-8"?>
<banks>
    <bank id="1">
        <name>Barclays Bank</name>
        <headquarter>London</headquarter>
    </bank>
    <bank id="2">
        <name>Goldman Sachs</name>
        <headquarter>NewYork</headquarter>
    </bank>
    <bank id="3">
        <name>ICBC</name>
        <headquarter>Beijing</headquarter>
    </bank>
</banks>

Java File: XmlStringInJava .java

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;
/**
  * Java Program to read XML as String using BufferedReader
  * open source library.
  */
public class XmlStringInJava {

    public static void main(String[] args) throws IOException {

        // our XML file for this example
        File xmlFile = new File("file.xml");

        // Let's get XML file as String using BufferedReader
        // FileReader uses platform's default character encoding
        // if you need to specify a different encoding, use InputStreamReader
        Reader fileReader = new FileReader(xmlFile);
        BufferedReader bufReader = new BufferedReader(fileReader);

        StringBuilder sb = new StringBuilder();
        String line = bufReader.readLine();
        while( line != null){
            sb.append(line).append("\n");
            line = bufReader.readLine();
        }
        String xml2String = sb.toString();
        System.out.println("XML to String using BufferedReader : ");
        System.out.println(xml2String);
        xml2String = xml2String.replace("bank kaka","bank id");
        System.out.println("After Replacing: ");
        System.out.println(xml2String);

        bufReader.close();
      }
}

No comments:

Post a Comment