简体   繁体   English

通过Java读取XML,替换文本和写入相同的XML文件

[英]Read XML, Replace Text and Write to same XML file via Java

Currently I am trying something very simple. 目前我正在尝试一些非常简单的事情 I am looking through an XML document for a certain phrase upon which I try to replace it. 我正在浏览一个XML文档,查找我试图替换它的某个短语。 The problem I am having is that when I read the lines I store each line into a StringBuffer. 我遇到的问题是,当我读取行时,我将每行存储到StringBuffer中。 When I write the it to a document everything is written on a single line. 当我将它写入文档时,所有内容都写在一行上。

Here my code: 这是我的代码:

File xmlFile = new File("abc.xml")
BufferedReader br = new BufferedReader(new FileReade(xmlFile));
String line = null;
while((line = br.readLine())!= null)
{
    if(line.indexOf("abc") != -1)
    {
        line = line.replaceAll("abc","xyz");
    }         
    sb.append(line);                
}
br.close();

BufferedWriter bw = new BufferedWriter(new FileWriter(xmlFile));
bw.write(sb.toString());
bw.close();

I am assuming I need a new line character when I prefer sb.append but unfortunately I don't know which character to use as "\\n" does not work. 我假设我需要一个新的行字符,当我更喜欢sb.append但不幸的是我不知道使用哪个字符“\\ n”不起作用。

Thanks in advance! 提前致谢!

PS I figured there must be a way to use Xalan to format the XML file after I write to it or something. PS我认为必须有一种方法可以在我写入XML文件之后使用Xalan格式化XML文件。 Not sure how to do that though. 不知道该怎么做。

The readline reads everything between the newline characters so when you write back out, obviously the newline characters are missing. readline读取换行符之间的所有内容,因此当您回写时,显然缺少换行符。 These characters depend on the OS: windows uses two characters to do a newline, unix uses one for example. 这些字符取决于操作系统:Windows使用两个字符来换行,例如unix使用一个换行符。 To be OS agnostic, retrieve the system property "line.separator": 要与操作系统无关,请检索系统属性“line.separator”:

String newline = System.getProperty("line.separator");

and append it to your stringbuffer: 并将其附加到您的stringbuffer:

sb.append(line).append(newline);

Modified as suggested by Brel, your text-substituting approach should work, and it will work well enough for simple applications. 根据Brel的建议进行修改,您的文本替换方法应该可行,并且对于简单的应用程序来说它将运行良好。

If things start to get a little hairier, and you end up wanting to select elements based on their position in the XML structure, and if you need to be sure to change element text but not tag text (think <abc>abc</abc> ), then you'll want to call in in the cavalry and process the XML with an XML parser. 如果事情开始变得有点毛茸茸,你最终想要根据它们在XML结构中的位置选择元素,如果你需要确保更改元素文本而不是标记文本(想想<abc>abc</abc> ),那么你将要在骑兵中调用并使用XML解析器处理XML。

Essentially you read in a Document using a DocuemntBuilder , you hop around the document's nodes doing whatever you need to, and then ask the Document to write itself back to file. 基本上,您使用DocuemntBuilderDocumentDocuemntBuilder ,您可以在文档的节点上DocuemntBuilder执行任何操作,然后让Document将自身写回文件。 Or do you ask the parser? 或者你问解析器? Anyway, most XML parsers have a handful of options that let you format the XML output: You can specify indentation (or not) and maybe newlines for every opening tag, that kinda thing, to make your XML look pretty. 无论如何,大多数XML解析器都有一些允许您格式化XML输出的选项:您可以为每个开始标记指定缩进(或不指定)和新行,这样可以使您的XML看起来很漂亮。

Sb would be the StringBuffer object, which has not been instantiated in this example. Sb将是StringBuffer对象,在此示例中尚未实例化。 This can added before the while loop: 这可以在while循环之前添加:

StringBuffer sb =  new StringBuffer();
Scanner scan = new Scanner(System.in);
String filePath = scan.next();
String oldString = "old_string";
String newString = "new_string";
String oldContent = "";
BufferedReader br = null;
FileWriter writer = null;
File xmlFile = new File(filePath);
try {
    br = new BufferedReader(new FileReader(xmlFile));
    String line = br.readLine();
    while (line != null) {
        oldContent = oldContent + line + System.lineSeparator();
        line = br.readLine();
    }
    String newContent = oldContent.replaceAll(oldString, newString);
    writer = new FileWriter(xmlFile);
    writer.write(newContent);
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        scan.close();
        br.close();
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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