您的位置:首页 > 其它

XmlTextWriter 类

2008-10-06 17:50 337 查看
XmlTextWriter对象简介
XmlTextWriter对象包含了很多可用于在创建XML文件时添加元素和属性到XML文件里的方法,比较重要的有:
WriteStartDocument()-创建XML文件首先就需要用到这个方法,它是在创建XML文件的第一行代码,用来指定该文件是XML文件以及设置它的编码类型;
WriteStartElement(string)-这个方法的作用是在XML文件中创建新元素,你可以通过String参数设置元素的名称(当然了,你还可以使用optional关键字指定一个可选的参数);
WriteElementString(name, text_value)-如果你需要创建一个除了字符,什么也没有的(如不嵌套元素)的元素,你可以使用该方法;
WriteEndElement()-对应WriteStartElement(string)方法,作为一个元素的结尾;
WriteEndDocument()-XML文件创建完成后使用该方法结束;
Close()-关闭所有的文本流,把创建的XML文件输出到指定位置。

使用XmlTextWriter对象创建XML文件,需要在类构造器中指定文件的类型,而且编码类型必须是System.Text.Encoding,如:System.Text.Encoding.ASCII, System.Text.Encoding.Unicode及System.Text.Encoding.UTF8,在XmlTextWriter类构造器指定为何种类型,在输出XML文件将以那种流文件形式输出。

使用XmlTextWriter对象创建一个简单的XML文件
接下来,我们示范一下如何使用XmlTextWriter对象来创建一个简单的XML文档,并把它保存到指定的位置,这个XML文件将包含访问该文件的用户的相关信息,它的输出格式如下:
<userInfo>
<browserInfo>
<urlReferrer>URL referrer info</urlReferrer>
<userAgent>User agent referrer info</userAgent>
<userLanguages>languages info</userLanguages>
</browserInfo>
<visitInfo timeVisited="date/time the page was visited">
<ip>visitor's IP address</ip>
<rawUrl>raw URL requested</rawUrl>
</visitInfo>
</userInfo>
选用这个有这种结构的XML文件为输出对象,是为了可以在这里使用所有先前讲过的方法,方便阐述。

如下便是创建该XML文件所需的ASP.NET代码:
<%@ Import Namespace="System.Xml" %>
<%@ Import Namespace="System.Text" %>
<script language="C#" runat="server">
void Page_Load(object sender, EventArgs e)
{
// Create a new XmlTextWriter instance
XmlTextWriter writer = new
XmlTextWriter(Server.MapPath("userInfo.xml"), Encoding.UTF8);

// start writing!
writer.WriteStartDocument();
writer.WriteStartElement("userInfo");

// Creating the <browserInfo> element
writer.WriteStartElement("browserInfo");

if (Request.UrlReferrer == null)
writer.WriteElementString("urlReferrer", "none");
else
writer.WriteElementString("urlReferrer",
Request.UrlReferrer.PathAndQuery);

writer.WriteElementString("userAgent", Request.UserAgent);
writer.WriteElementString("userLanguages",
String.Join(", ", Request.UserLanguages));
writer.WriteEndElement();

// Creating the <visitInfo> element
writer.WriteStartElement("visitInfo");
writer.WriteAttributeString("timeVisited", DateTime.Now.ToString());
writer.WriteElementString("ip", Request.UserHostAddress);
writer.WriteElementString("rawUrl", Request.RawUrl);
writer.WriteEndElement();

writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();
}

首先我们要注意是否有导入System.Xml and System.Text命名空间,然后我们在Page_Load事件中创建一个XmlTextWriter对象实例,并且指定创建的XML文件保存为userInfo.xml文件和它的编码类型为UTF8(a translation of 16-bit unicode encoding into 8-bits),然后使用WriteStartElement(elementName)方法来创建嵌套了其他元素的元素,并以WriteEndElement()作为结束,此外,我们使用WriteElementString(elementName, textValue)方法来创建最底层即没有嵌套其他元素的元素。

在浏览器窗口中输出XML文件
先前的例子示范了如何使用XmlTextWriter对象创建xml文件以及把它保存为一个文件,这个文件可能是你所需要的,但是有时候,我们需要把创建的XML文件在浏览器上显示出来,这个时候,我们可以使用上例代码创建userInfo.xml文件,然后打开它,再使用Response.Write()把它输出,但是这种方法并不是很好。
一个好的方法是立即把XmlTextWriter对象的结果显示在浏览器上,要实现这个功能非常地容易,只需要在上例的代码基础上修改一行代码就可以了,在XmlTextWriter的类构造器中,我们不指定为一个文件路径,而是指定为Response.OutputStream,以使ASP.NET程序直接输出XML流到浏览器中,而不是保存为一个文件,当然了,你还可以设定<@ Page ... >指令中的MIME类型为text/xml来实现同样的功能,但是我建议你不要用这种方法来实现,因为有些浏览器不认得该格式而把它当做html来解释(它将蕴藏所有的xml元素,并删除所有的空格)。

下面列出了上例修改后的部分代码,修改过的代码将一些粗体显示:
<@ Page ContentType="text/xml" %>
<%@ Import Namespace="System.Xml" %>
<%@ Import Namespace="System.Text" %>
<script language="C#" runat="server">
void Page_Load(object sender, EventArgs e)
{
// Create a new XmlTextWriter instance
XmlTextWriter writer = new
XmlTextWriter(Response.OutputStream, Encoding.UTF8);

// start writing!
...
}

XmlTextWriter类可以把XML写入一个流、文件或TextWriter对象中。

简单例子:
private void button2_Click(object sender, System.EventArgs e)
{
string filename = "booknew.xml";
XmlTextWriter tw = new XmlTextWriter(filename,null);
tw.Formatting = Formatting.Indented;
tw.WriteStartDocument();

tw.WriteStartElement("book");
tw.WriteAttributeString("genre","Mystery");
tw.WriteAttributeString("publicationdate","2001");
tw.WriteAttributeString("ISBN","123456789");
tw.WriteElementString("title","Case of the Missing Cookie");
tw.WriteStartElement("author");
tw.WriteElementString("name","Cookie Monster");
tw.WriteEndElement();
tw.WriteElementString("price","9.99");
tw.WriteEndElement();
tw.WriteEndDocument();
tw.Flush();
tw.Close();
}

代码生成后的xml文档booksnew.xml:

<?xml version="1.0"?>
<book genre="Mystery" publicationdate="2001" ISBN="123456789">
<title>Case of the Missing Cookie</title>
<author>
<name>Cookie Monster</name>
</author>
<price>9.99</price>
</book>

可以看出,在XML文档中,有一个起始方法和结束方法(WriteStartElement和WriteEndElement),其他专用的写入方法:WriteCData可以输入一个Cdata;WriteComment以正确的XML格式写入注释。WriteChars写入字符缓冲区的内容。

利用.NET DOM,XmlDocument创建一个文档

private XmlDocument doc= new XmlDocument();
private void button2_Click(object sender, System.EventArgs e)
{
XmlDeclaration newDec = doc.CreateXmlDeclaration("1.0",null,null);
doc.AppendChild(newDec);
XmlElement newRoot = doc.CreateElement("newBookstore");
doc.AppendChild(newRoot);

//创建一个新的book元素
XmlElement newBook = doc.CreateElement("book");
//创建并设置book元素的属性
newBook.SetAttribute("genre","Mystery");
newBook.SetAttribute("publicationdate","2001");
newBook.SetAttribute("ISBN","123456789");
//创建一个title元素
XmlElement newTilte = doc.CreateElement("title");
newTilte.InnerText ="Case of the Missing Cookie";
newBook.AppendChild(newTilte);
//创建author元素
XmlElement newAuthor = doc.CreateElement("author");
newBook.AppendChild(newAuthor);

XmlElement newName = doc.CreateElement("name");
newName.InnerText = "C.Monster";
newAuthor.AppendChild(newName);

XmlElement newPrice = doc.CreateElement("price");
newPrice.InnerText = "9.95";
newBook.AppendChild(newPrice);
doc.DocumentElement.AppendChild(newBook);
XmlTextWriter tr = new XmlTextWriter("booksEdit.xml",null);
tr.Formatting = Formatting.Indented;
doc.WriteContentTo(tr);
tr.Close();
}

代码生成后的文档:
<?xml version="1.0"?>
<newBookstore>
<book genre="Mystery" publicationdate="2001" ISBN="123456789">
<title>Case of the Missing Cookie</title>
<author>
<name>C.Monster</name>
</author>
<price>9.95</price>
</book>
</newBookstore>

如果从头开始创建一个文档,可以使用XmlTextWrite。还可以使用XmlDocument。使用哪个比较好?如果要写入Xml流的数据已经准备好,最好的选择用XmlTextWriter类,但是如果需要一次建立Xml文档的一小部分,在不同的地方插入节点,用XmlDocument创建文档就比较好。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: