簡體   English   中英

通過Java讀取XML,替換文本和寫入相同的XML文件

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

目前我正在嘗試一些非常簡單的事情 我正在瀏覽一個XML文檔,查找我試圖替換它的某個短語。 我遇到的問題是,當我讀取行時,我將每行存儲到StringBuffer中。 當我將它寫入文檔時,所有內容都寫在一行上。

這是我的代碼:

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();

我假設我需要一個新的行字符,當我更喜歡sb.append但不幸的是我不知道使用哪個字符“\\ n”不起作用。

提前致謝!

PS我認為必須有一種方法可以在我寫入XML文件之后使用Xalan格式化XML文件。 不知道該怎么做。

readline讀取換行符之間的所有內容,因此當您回寫時,顯然缺少換行符。 這些字符取決於操作系統:Windows使用兩個字符來換行,例如unix使用一個換行符。 要與操作系統無關,請檢索系統屬性“line.separator”:

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

並將其附加到您的stringbuffer:

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

根據Brel的建議進行修改,您的文本替換方法應該可行,並且對於簡單的應用程序來說它將運行良好。

如果事情開始變得有點毛茸茸,你最終想要根據它們在XML結構中的位置選擇元素,如果你需要確保更改元素文本而不是標記文本(想想<abc>abc</abc> ),那么你將要在騎兵中調用並使用XML解析器處理XML。

基本上,您使用DocuemntBuilderDocumentDocuemntBuilder ,您可以在文檔的節點上DocuemntBuilder執行任何操作,然后讓Document將自身寫回文件。 或者你問解析器? 無論如何,大多數XML解析器都有一些允許您格式化XML輸出的選項:您可以為每個開始標記指定縮進(或不指定)和新行,這樣可以使您的XML看起來很漂亮。

Sb將是StringBuffer對象,在此示例中尚未實例化。 這可以在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