如何从xml java中搜索和删除一些值

时间:2016-01-20 07:25:16

标签: java xml xml-parsing

我有一个xml abc.xml

<soapenv:Envelope>
   <soapenv:Header/>

   <soapenv:Body>
      <mes:SomeRq>

         <RqID>?</RqID>

         <MsgRqHdr>
         ....
      </mes:SomeRq>
   </soapenv:Body>
</soapenv:Envelope>

我有没有办法从这个xml中搜索mes:并将其替换为ins:

提前致谢。

public static void findreplcae(String strFilePath) throws IOException {
    String currentString = "mes:";
    String changedString = "ins:";
    BufferedReader reader = new BufferedReader(new FileReader(strFilePath));

    StringBuffer currentLine = new StringBuffer();
    String currentLineIn;
    while ((currentLineIn = reader.readLine()) != null) {
        System.out.println(currentLineIn);
        boolean bool = false;
        String trimmedLine = currentLineIn.trim();
        System.out.println(trimmedLine);
        if (trimmedLine.contains(currentString)) {
            trimmedLine.replace(currentString, changedString);
            bool = true;
            if (bool != true) {
                currentLine = currentLine.append(currentLineIn + System.getProperty("line.separator"));
            }
        }
        reader.close();
        BufferedWriter writer = new BufferedWriter(new FileWriter(strFilePath));
        writer.write(currentLine.toString());
        writer.close();
    }
}

2 个答案:

答案 0 :(得分:2)

将其解析为文本文件并不是一个好主意。 DocumentBuilder.parse要解析文件,请致电getDocumentElement()并检查getPrefix。如果匹配,请替换为setPrefix()。请注意,如果尚未注册,则必须注册前缀。

检查this page以获取教程。

答案 1 :(得分:1)

一些问题:

  1. bool = true; if (bool != true) { currentLine = currentLine.append(currentLineIn + System.getProperty("line.separator")); } ,结果是返回,因此您必须将其存储在某处。请参阅here
  2. 这应该做什么?

    String currentString = "mes:";
    String changedString = "ins:";
    try {
        BufferedReader reader = new BufferedReader(new FileReader(strFilePath));
    
        StringBuffer newContents = new StringBuffer();
        String currentLineIn = null;
        while ((currentLineIn = reader.readLine()) != null) {
            String trimmedLine = currentLineIn.trim();
            if (trimmedLine.contains(currentString)) {
                newContents.append(trimmedLine.replace(currentString, changedString));
            }
            else {
                newContents.append(trimmedLine);
            }
            newContents.append(System.getProperty("line.separator"));
        }
    
        reader.close();
    
        BufferedWriter writer = new BufferedWriter(new FileWriter(strFilePath));
        writer.write(newContents.toString());
        writer.close();
    
    } catch (IOException e) {
        // TODO handle it
    }
    
  3. 在循环阅读时不要关闭阅读器。
  4. 如果你想覆盖原始文件,这应该做(虽然我不确定,如果你真的想修剪线条):

    {{1}}