AutoCAD 3DMAX C语言 Pro/E UG JAVA编程 PHP编程 Maya动画 Matlab应用 Android
Photoshop Word Excel flash VB编程 VC编程 Coreldraw SolidWorks A Designer Unity3D
 首页 > XML

在.NET Framework中轻松处理XML数据(四)

51自学网 http://www.51zixue.net

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("<");



读写流

有趣的是,reader(阅读器)和writer类提供了基于Base64 和BinHex编码的读写数据流的方法。WriteBase64 和 WriteBinHex方法的功能与其它的写方法的功能存在着细微的差别。它们都是基于流的,这两个方法的功能像一个byte数组而不是一个string。下面的代码首先把一个string转换成一个byte数组,然后把它们写成一个Base64 编码流。Encoding类的GetBytes静态方法完成转换的任务:

writer.WriteBase64(

Encoding.Unicode.GetBytes(buf),

0, buf.Length*2);

 
 

上一篇:XML文档搜索使用小结  下一篇:Web设计中如何使用XML数据