CSDN专家博客精华版

为人民服务!
  首页  :: 新随笔  :: 管理

Java下简单模仿.net的XmlWriter

Posted on 2007-12-17 10:18  csdnexpert  阅读(78)  评论(0编辑  收藏  举报

import java.util.Stack;


/**
 * @author qinjinwei
 *
 */
public class XmlWriter {

 
 private static char IndentChars = '\t';
 private static char LeftChars = '<';
 private static char RightChars = '>';
 private static char EndChars = '/';
 private Stack stack = new Stack();
 private StringBuffer buffer = new StringBuffer();
 
 
 public void WriteStartElement(String elementName)
 {
  String token = StartElement(elementName );
  WriteWhitespace();
  buffer.append(token);
  buffer.append("\r\n");
  stack.push(elementName);

 }
 
 public void WriteString(String elementName,String elementValue)
 {
  WriteStartElement(elementName);
  WriteString(elementValue);
  WriteEndElement();
 }
 
 private void WriteString(String value)
 {
  WriteWhitespace();
  //WriteWhitespace(1);
  buffer.append(value);
  buffer.append("\r\n");
 }
 
 public void WriteEndElement()
 {
  if(!stack.isEmpty())
  {
   String elementName = (String)stack.pop();
      String token = EndElement(elementName );
      WriteWhitespace();
   buffer.append(token);
   buffer.append("\r\n");
  }
 }
 
 private void WriteWhitespace(int count)
 {
  for (int i = 0; i < count; i++) {
   buffer.append(IndentChars);
  }
 }

 private void WriteWhitespace()
 {
  WriteWhitespace( stack.size());
 }
 
 private String StartElement(String elementName)
 {
  return LeftChars + elementName + RightChars ;
 }
 
 private String EndElement(String elementName)
 {
  return LeftChars + "" + EndChars + elementName + RightChars ;
 }

 public String createXml()
 {
  return buffer.toString();
 }
}

/**
 * @author qinjinwei
 *
 */
public class test {

 public static void main(String[] args) {

  XmlWriter writer = new XmlWriter();
  writer.WriteStartElement("Class1");
  writer.WriteStartElement("Name");
  writer.WriteString("String","zhangsan");
  writer.WriteEndElement();
  writer.WriteEndElement();
  
  String result = writer.createXml();
  
  System.out.println(result);
 }

}

 



Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1600593