假定创建了XmlWriter的实例变量xmlWriter,下文中将使用此实例变量写Xml
1.如何使用XmlWriter写Xml文档声明
// WriteStartDocument方法可以接受一个bool参数(表示standalone,是否为独立文档)或者不指定参数standalone保持默认值
xmlWriter.WriteStartDocument(
false
|
true
);
|
注意在使用WriteStartDocument方法后最好调用xmlWrite.WriteEndDocument()方法来关闭所有可能未关闭标签
2.如何使用XmlWriter写xml节点以及属性
或者通过WriteElementString(string,string)方法写xml节点同时写下节点值,如下
3.如何写CData
xmlWriter.WriteStartElement(
"dog"
);
//写CData
xmlWriter.WriteCData(
"<strong>dog is dog</strong>"
);
xmlWriter.WriteEndElement();
|
4.如何使用XmlWriter添加注释
|
5.如何设置XmlWriter的输出格式,解决输出UTF-16问题
设置xml输出格式,需要通过XmlWriterSettings类,如下代码
完整的代码示例如下:
/*玉开技术博客 http://www.cnblogs.com/yukaizhao */
using
System;
using
System.Collections.Generic;
using
System.Text;
using
System.IO;
using
System.Xml;
namespace
UseXmlWriter
{
class
Program
{
static
void
Main(
string
[] args)
using
(MemoryStream ms =
new
MemoryStream())
{
XmlWriterSettings settings =
new
XmlWriterSettings();
//要求缩进
settings.Indent =
true
;
//注意如果不设置encoding默认将输出utf-16
settings.Encoding =
false
);
//设置换行符
settings.NewLineChars = Environment.NewLine;
using
(XmlWriter xmlWriter = XmlWriter.Create(ms,settings))
{
//写xml文件开始<?xml version="1.0" encoding="utf-8" ?>
xmlWriter.WriteStartDocument(
//写根节点
xmlWriter.WriteStartElement(
"root"
);
//写字节点
xmlWriter.WriteStartElement(
"cat"
);
xmlWriter.WriteString(
"I'm a cat"
);
xmlWriter.WriteEndElement();
xmlWriter.WriteElementString(
"pig"
,
"pig is great"
);
xmlWriter.WriteStartElement(
"dog"
);
//写CData
xmlWriter.WriteCData(
"<strong>dog is dog</strong>"
);
xmlWriter.WriteEndElement();
xmlWriter.WriteEndDocument();
}
string
xml = Encoding.UTF8.GetString(ms.ToArray());
Console.WriteLine(xml);
}
Console.Read();
}
}
|