实际上,我需要替换源 xml 中的一些标签并将文件写入新文件。这里我的代码工作正常,但现在无法打开输出 xml。在输出 xml 中我有一些泰米尔语单词。是不是文件打不开的原因
public class dxml {
public static StringBuffer sb = new StringBuffer() ;
public static void main(String [] args) throws Exception {
File xmlFile = new File("/home/dev702/Desktop/axl/Data Entry.xml");
BufferedReader br = new BufferedReader(
new FileReader("/home/dev702/Desktop/axl/Data Entry.xml"));
String line = null;
int linecount = 1;
FileWriter fw;
BufferedWriter bw = null;
fw = new FileWriter("/home/dev702/Desktop/axl/Data_Entry_OPT.xml") ;
bw = new BufferedWriter(fw);
while((line = br.readLine())!= null)
{
if(linecount > 2)
{
line = line.replaceAll("Data_x0020_Entry_x0020_Date",
"DataEntryDate");
//bw.write(line);
}
bw.write(line);
linecount++;
System.out.println(line);
}
bw.close();
fw.close();
}
}
最佳答案
如果您想将 XML 转换为另一种形式的 XML,您应该使用 XSLT 来实现这一点。 Java 支持转换两个文档...下面是如何实现此目的的代码片段。
前提实际上是您将原始 XML 放入文档中,设置要使用的 XSLT 并将其转换为另一个文档。
使用 XSLT 的范围不在本回复范围内。我建议使用 Altova 优秀的 XMLSpy 来测试您的 XSLT。
public class Mapper {
public Document convert(Document originalDocument, Resource xsltResource) throws TransformerException, ParserConfigurationException,
JAXBException, IOException, SAXException {
/**
* You'll need to create your documentBuilder to build the new document.
*/
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
/**
* Set up your transformer factory, you'll need to pass your XSLT file in as an inputstream
* I've passed it in here as a method arg and it's a Spring Resource but you can do it however you like.
*/
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory
.newTransformer(new StreamSource(xsltResource.getInputStream()));
/**
* Set the encoding to avoid headaches.
*/
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
/**
* Create a BAoS to hold your original document.
*/
ByteArrayOutputStream os = new ByteArrayOutputStream();
transformer.transform(new DOMSource(originalDocument), new StreamResult(os));
/**
* Do the transformation.
*/
return documentBuilder.parse(new InputSource(new StringReader(os.toString("UTF-8"))));
}
}
关于java - 无法使用java将文件从一个xml写入另一个xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22068364/