简体   繁体   中英

I need to read a xml file and change the id of each tag to id+tagname

I need to read a file and find and replace some text in the same file without closing reader.

Suggest any easy ways...

Iam reading the file as follows. How can I write it to the same file.

private static void readFile(String path) throws IOException {
        makeFolderStructure(path);
        for (String xmlNameString : xmlFileNamesList) {
            FileReader xmlFile = new FileReader(
                    path + "\\xml\\" + xmlNameString + ".xml");
            BufferedReader br = new BufferedReader(xmlFile);
            try {
                String line = br.readLine();
                while (line != null) {
                    if (line.contains("<") && line.indexOf(" ") != -1) {
                        String tagName = line.substring(line.indexOf("<") + 1,
                                line.indexOf(" "));
                        if (line.indexOf("id") != -1) {
                            Pattern p = Pattern.compile("\"([^\"]*)\"");
                            Matcher m = p.matcher(line);
                            while (m.find()) {
                                String tagId = (m.group(1));
                                System.out.println(tagId+"_"+tagName);
                            }
                        }
                    }
                    line = br.readLine();
                }
            } finally {
                br.close();
            }
        }
    }

If you like reading: Check this out https://docs.oracle.com/cd/B28359_01/appdev.111/b28394/adx_j_parser.htm

If you don't:

There are a number of XML parsers out there

I highly recommend you to check them out. Most of them are very easy to use check out the documentation of each one of them and decide which one you would like to use. What you're trying to do with the above code is reinventing the wheel, take a look at the above-mentioned API's and focus on writing new code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM