2

可能重复:
用 Java 写入 XML 文件

我将以下 XML 文本作为字符串。

<someNode>
    <id>A124</id>
    <status>404</status>
    <message>No data</message>
</someNode>

我将上述 XML 数据作为字符串。是否可以将文本转换为 XML 文件并将生成的 XML 文件存档?

谢谢!

4

5 回答 5

1
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
Document doc = docBuilder.parse(new InputSource(new StringReader(theString)));
于 2012-12-06T16:01:53.120 回答
0

您可以使用java.io.FileWriter来保存您的文件。

String fileData = "<sample><xml>data</xml></sample>";
File outputFile = new File("someFile.xml");
BufferedWriter bw = null;
try{
    bw = new BufferedWriter(new FileWriter(outputFile));
    bw.write(fileData);
}
catch(IOException e)
{
    e.printStackTrace();
}
finally
{
    try{bw.close();}catch(Exception e){}
}

如果您需要像Kazekage Gaara所说的那样操作 xml:

DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
Document doc = docBuilder.parse(new InputSource(new StringReader(theString)));

为了拯救你,你可以按照我上面所说的去做。要将文档转换回字符串:

fileData = doc.toString();
于 2012-12-06T16:04:30.917 回答
0
public class StringToXML {  
public static void main(String[] args) {  
    String xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"></soap:Envelope>";  

     DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  

    DocumentBuilder builder;  
    try  
    {  
        builder = factory.newDocumentBuilder();  

        // Use String reader  
        Document document = builder.parse( new InputSource(  
                new StringReader( xmlString ) ) );  

        TransformerFactory tranFactory = TransformerFactory.newInstance();  
        Transformer aTransformer = tranFactory.newTransformer();  
        Source src = new DOMSource( document );  
        Result dest = new StreamResult( new File( "xmlFileName.xml" ) );  
        aTransformer.transform( src, dest );  
    } catch (Exception e)  
    {  
        // TODO Auto-generated catch block  
        e.printStackTrace();  
    }  
}  

此信息很有帮助。

谢谢,帕万

于 2012-12-06T16:05:57.753 回答
0

就这么简单:

String text = "<your><xml>data</xml></your>";
Writer writer = new FileWriter("/tmp/filename.xml");
writer.write(text);
writer.flush();
writer.close();
于 2012-12-06T16:09:15.737 回答
0

我建议使用commons-io。它有一个方法可以完成您需要的一切。

代码看起来像

FileUtils.writeStringToFile(new File("filename.xml"), xml);
于 2012-12-06T16:19:30.743 回答