figure 7 states for xml writer
state
description
attribute
the writer enters this state when an attribute is being written
closed
the close method has been called and the writer is no longer available for writing operations
content
the writer enters this state when the content of a node is being written
element
the writer enters this state when an element start tag is being written
prolog
the writer is writing the prolog of a well-formed xml 1.0 document
start
the writer is in an initial state, awaiting for a write call to be issued
writer 把输出文本存在内部的一个缓冲区内。一般情况下,缓冲区会被刷新或者被清除,当writer被关闭前xml文本应该要写出。在任何时你都可以通过调用flush方法清空缓冲区,把当前的内容写到流中(通过basestream属性暴露流),然后释放部分占用的内存,writer仍保持为打开状态(open state),可以继续操作。注意,虽然写了部分的文档内容,但是在writer没有关闭前其它的程序是不能处理该文档的。
可以用两种方法来写属性节点。第一种方法是用writestartatribute方法去创建一个新的属性节点,更新writer的状态。接着用writestring方法设置属性值。写完后,用writeendelement方法结束该节点。另外,你也可以用writeattributestring方法去创建新的属性节点,当writerr的状态为element时,writerattributestring开始工作,它单独创建一个属性。同样的,writestartelement方法写节点的开始标签(<),然后你可以随意的设置节点的属性和文本内容。元素节点的闭标签都带”/ >”。如果想写闭标签可以用writefullendelement方法来写。
应该避免传送给写方法的文本中包含敏感的标记字符,例如小于号(<)。用writeraw方法写入流的字符串不会被解析,我们可以用它来对xml文档写入特殊的字符串。下面的两行代码,第一行输出的是”<”,第二行输出”<”:
writer.writestring("<");
writer.writeraw("<");