【问题标题】:Writing stax XML to String将 stax XML 写入字符串
【发布时间】:2016-05-14 09:02:18
【问题描述】:

我正在使用 stax 创建我的 Web 应用程序所需的 XML 文档。 目前我正在这样的文件中创建我的 XML:

    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    String output=null;
     try 
     {
             XMLStreamWriter writer = factory.createXMLStreamWriter(
                     new FileWriter("C:\\Junk\\xmlDoc.xml"));
             writer.writeStartDocument();
             writer.writeStartElement("TagName1");
             writer.writeAttribute("AAA", "BBB");
             writer.writeEndElement();
             writer.writeEndDocument();             
             writer.flush();
             writer.close();
     } 
     catch (XMLStreamException e) 
     {
         e.printStackTrace();
     } 
     catch (IOException e) 
     {      
        e.printStackTrace();
     } 

但是 xml 文件不是我想要的,我需要在 String 中创建我的 XML。 不幸的是,我不知道我需要哪个 OutputStream 对象而不是 FileWriter

【问题讨论】:

    标签: java xml java-io stax


    【解决方案1】:

    你需要一个java.io.StringWriter:

    FileWriter 一样,它派生自Writer,可以传递给factory.createXMLStreamWriter。完成后,您可以将写入的内容转换为字符串。

    StringWriter stringOut = new StringWriter();
    XMLStreamWriter writer = factory.createXMLStreamWriter(stringOut);
    ... // write XML
    
    String output = stringOut.toString();
    

    【讨论】:

      猜你喜欢
      • 2016-03-10
      • 2012-03-19
      • 2011-06-06
      • 2016-03-04
      • 1970-01-01
      • 2011-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多