Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package xmlAttributeReplacer;
- import java.io.BufferedWriter;
- import java.io.File;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Scanner;
- public class AttributeReplacer {
- // Global variables
- static String path = "C:\\User\\Documents\\";
- static String filename = "entity names.txt";
- static String filename2 = "entities2.xml";
- static String attribute = "name";
- public static void main(String[] args) throws IOException {
- // Read the list of values
- // Create array
- List<String> values1 = new ArrayList<String>();
- //Start the scanner
- File f = new File(path + "Translated files\\" + filename);
- Scanner s = new Scanner(f);
- //Go through the lines and save them into the array
- while(s.hasNext()) {
- String line = s.nextLine();
- values1.add(line);
- }
- s.close();
- String[] values = values1.toArray(new String[0]);
- // Read the main file
- // Create string
- String mainFile = "";
- //Start the scanner
- File f2 = new File(path + "Raw files\\" + filename2);
- Scanner s2 = new Scanner(f2);
- //Go through the lines and add them to the string
- while(s2.hasNext()) {
- String line = s2.nextLine();
- mainFile = mainFile + "\n" + line;
- }
- s2.close();
- // Replace all ocurrences of the regex pattern in the main file with the elements of the array using substitution so that the
- // same ocurrences aren't matched more than once
- for(int i = 0; i < values.length; i++) {
- values[i] = values[i].replace("$", "\\$"); // This is a fix for dollar signs which otherwise cause problems
- mainFile = mainFile.replaceFirst(attribute + "=\".*?\"", attribute + "!!=\"" + values[i] + "\"");
- }
- // Remove the substitutes
- for(int i = 0; i < values.length; i++) {
- mainFile = mainFile.replaceFirst(attribute + "!!", attribute);
- }
- // Save to file in output folder
- // Initiate the FileWriter with the designated file path
- FileWriter f3 = new FileWriter(path + "Output\\" + filename2);
- BufferedWriter bW = new BufferedWriter(f3);
- bW.write(mainFile);
- bW.close();
- System.out.println("Done!");
- }
- }
Add Comment
Please, Sign In to add comment