java替换xml换行符,XML转换和换行符

ok, i have code which works on this xml:

1

abcdef

2

abcdef

abcdef

The code splits initial XML file into 2 files, and also tries to add some tags afterwards.

import java.io.*;

import java.io.FileReader;

import java.io.FileWriter;

import javax.xml.stream.XMLInputFactory;

import javax.xml.stream.XMLOutputFactory;

import javax.xml.stream.XMLStreamConstants;

import javax.xml.stream.XMLStreamReader;

import javax.xml.stream.XMLStreamWriter;

import javax.xml.transform.Transformer;

import javax.xml.transform.TransformerFactory;

import javax.xml.transform.stax.StAXSource;

import javax.xml.transform.stax.StAXResult;

import javax.xml.transform.stream.StreamResult;

import javax.xml.stream.XMLStreamException;

import java.io.FileOutputStream;

import javax.xml.transform.OutputKeys;

public class ver2 {

public static void main(String[] args) throws Exception {

XMLInputFactory xif = XMLInputFactory.newInstance();

xif.setProperty("javax.xml.stream.isCoalescing", true);

XMLStreamReader xsr = xif.createXMLStreamReader(new FileReader("out.xml"));

XMLOutputFactory factory = XMLOutputFactory.newInstance();

TransformerFactory tf = TransformerFactory.newInstance();

Transformer t = tf.newTransformer();

xsr.nextTag();

int i=0;

while(xsr.hasNext()) {

int event = xsr.next();

if (event== XMLStreamConstants.START_ELEMENT){

if (xsr.getLocalName().equals("record")){

i++;

File file = new File(i + ".txt");

try {

XMLStreamWriter writer = factory.createXMLStreamWriter(new FileWriter(file));

t.transform(new StAXSource(xsr), new StAXResult(writer));

writer.writeStartElement("addSomeTags");

writer.writeCharacters("\r\n");

writer.writeStartElement("somestuff");

writer.writeEndElement();

writer.writeEndElement();

writer.flush();

writer.close();

} catch (XMLStreamException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

}

}

The problem is that when i open resulting files in notepad, notepad doesn't recognize linebreak characters. (probably because they are "/n", not "/n/r") At the same time if i transformed StaxSource into StreamResult (not employing XMLStreamWriter) notepad would recognize them. Can you explain why it happens, and, how to make it well-formated?

(but as you understand it IS presented properly in wordPad or other text Editors including this one)

Also, if this way is perverse in some way, please, let me know.

解决方案

Change code from

writer.writeCharacters("\r\n");

to

write.writeCharacters(System.getProperty("line.separator"));

This is more generic and should work better

than \r\n which would only work on windows.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值