简体   繁体   English

使用XMLStreamWriter附加到XML

[英]Appending to XML with XMLStreamWriter

Basically the app writes the contents of a Collection to XML. 基本上,应用程序将Collection的内容写入XML。 I'm using XMLStreamWriter ( XMLOutputFactory.newInstance().createXMLStreamWriter(...) ) for this purpose. 我为此使用XMLStreamWriter( XMLOutputFactory.newInstance().createXMLStreamWriter(...) )。

Works great except for the fact that I can't get how to append data to an existing file. 除了无法获取将数据附加到现有文件的事实外,它的工作效果非常好。 Don't really like the idea of reading all of it first, appending the data in memory and then overwriting. 不太喜欢先读取所有内容,将数据附加到内存中然后进行覆盖的想法。 Or is it the only way? 还是唯一的方法?

Simply appending to an XML file will result in malformed XML. 简单地附加到XML文件将导致XML格式错误。 You should build the DOM and attach what new elements you need. 您应该构建DOM并附加所需的新元素。

If you're appending a top-level element, you can probably get away with doing what you want. 如果要添加顶级元素,则可能可以摆脱想要做的事情。 eg, If you have this file: 例如,如果您有此文件:

<some_element>
  <nested_element>
    ...
  </nested_element>
</some_element>

you can most likely get away with appending another some_element element. 您很可能可以通过附加另一个some_element元素来避免some_element

However, you're obviously screwed if there's an outer-level element, and you have to append an inner -level one. 但是,如果有一个外部级别的元素,显然很麻烦,并且必须附加一个内部级别的元素。 For instance, suppose you want to add a some_element element to this file: 例如,假设您要向此文件添加some_element元素:

<data>
  <some_element>
    <nested_element>
      ...
    </nested_element>
  </some_element>
</data>

In general, you're far better off reparsing the document, then rewriting it. 通常,最好重新分析文档,然后重新编写文档。 If it's small, use a DOM-based parser; 如果很小,请使用基于DOM的解析器; it's easier. 更容易。 If the file is big, then use a SAX-based one. 如果文件很大,请使用基于SAX的文件。

Another approach is to build a new XML file and then merge it with the previous one by means of XSLT transformations . 另一种方法是构建一个新的XML文件,然后通过XSLT转换将其与上一个合并。 To apply XSLT stylesheets you should use Java XML Transformation API . 要应用XSLT样式表,您应该使用Java XML Transformation API

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM