Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 替换大型xml中的默认命名空间值_Java_Xml_Jaxb - Fatal编程技术网

Java 替换大型xml中的默认命名空间值

Java 替换大型xml中的默认命名空间值,java,xml,jaxb,Java,Xml,Jaxb,我有一个具有默认名称空间值的大型xml文件。如何在不使用java将整个文件加载到内存中的情况下替换该值 <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <customer xmlns="http://www.example.org/package"> <id>123</id> </customer> 123 应该成为 <?xml version="1.0

我有一个具有默认名称空间值的大型xml文件。如何在不使用java将整个文件加载到内存中的情况下替换该值

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer xmlns="http://www.example.org/package">
    <id>123</id>
</customer>

123
应该成为

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer xmlns="http://www.example.org/another">
    <id>123</id>
</customer>

123
有一种“黑客”方式:流式传输文件(使用读卡器和“UTF-8”字符集)并进行字符串替换


“真正”的方法是使用SAX或最好是StAX。您可以使用XMLEventReader和XMLEventWriter对xml进行流式处理,而无需将整个内容加载到内存中。当您使用错误的名称空间获取元素事件时,请使用正确的名称空间创建新元素事件并将其传递给编写器。

如果您的新替换字符串与前一个字符串大小相同,则有一种方法可以正常工作(或者如果替换字符串较小,至少可以添加空格):

下面是一个测试程序:

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class Test {

  public static void main( String[] args ) {
    try { 
      // NOTICE THE PACKAGE NAMES HAVE THE SAME SIZES
      String old_string = "xmlns=\"http://www.example.org/package\"";
      String new_string= "xmlns=\"http://www.example.org/another\"";

      RandomAccessFile raf = new RandomAccessFile( "test.xml", "rw" );
      String line;
      int byte_position = 0;
      while ( ( line = raf.readLine() ) != null ) {
        System.out.println( line );
        int index = line.indexOf( old_string );
        if( index !=-1 ) {
          raf.seek( byte_position + index );
          raf.writeBytes( new_string );
          raf.close();
          break;
        }
        // !!! +2 is for end line \n (use +4 if your end of lines is \n\r)
        byte_position += line.length() + 2; 
      }

    }
    catch ( Exception e ) {
      e.printStackTrace();
    }
  }
}
它所做的只是直接在右边部分进行随机访问。
我从逐行阅读开始,但当你在开始时(第二行)寻找一些东西时,这并不重要:之后会有一个休息,所以你不会阅读其他行…

你已经尝试了什么?使用文本编辑器从StackOverflow获得答案?或者
sed
用于流编辑?如果我不清楚,很抱歉。我需要用java来做这件事。你需要替换磁盘上文件中的值吗?还是需要在内存中对其进行修改以供以后处理?