使用XmlWriter寫Xml 假定創建了XmlWriter的實例變數xmlWriter,下文中將使用此實例變數寫Xml1.如何使用XmlWriter寫Xml文檔聲明 // WriteStartDocument方法可以接受一個bool參數(表示standalone,是否為獨立文檔)或者不指定參數st ...
使用XmlWriter寫Xml
假定創建了XmlWriter的實例變數xmlWriter,下文中將使用此實例變數寫Xml
1.如何使用XmlWriter寫Xml文檔聲明
// WriteStartDocument方法可以接受一個bool參數(表示standalone,是否為獨立文檔)或者不指定參數standalone保持預設值
xmlWriter.WriteStartDocument( false | true );
|
註意在使用WriteStartDocument方法後最好調用xmlWrite.WriteEndDocument()方法來關閉所有可能未關閉標簽
2.如何使用XmlWriter寫xml節點以及屬性
//寫節點
xmlWriter.WriteStartElement( "cat" );
//給節點添加屬性
xmlWriter.WriteAttributeString( "color" , "white" );
//給節點內部添加文本
xmlWriter.WriteString( "I'm a cat" );
xmlWriter.WriteEndElement();
|
或者通過WriteElementString(string,string)方法寫xml節點同時寫下節點值,如下
//通過WriteElementString可以添加一個節點同時添加節點內容
xmlWriter.WriteElementString( "pig" , "pig is great" );
|
3.如何寫CData
xmlWriter.WriteStartElement( "dog" );
//寫CData
xmlWriter.WriteCData( "<strong>dog is dog</strong>" );
xmlWriter.WriteEndElement();
|
4.如何使用XmlWriter添加註釋
xmlWriter.WriteComment( "this is an example writed by http://www.baidu.com/" );
|
5.如何設置XmlWriter的輸出格式,解決輸出UTF-16問題
設置xml輸出格式,需要通過XmlWriterSettings類,如下代碼
XmlWriterSettings settings = new XmlWriterSettings();
//要求縮進
settings.Indent = true ;
//註意如果不設置encoding預設將輸出utf-16
//註意這兒不能直接用Encoding.UTF8如果用Encoding.UTF8將在輸出文本的最前面添加4個位元組的非xml內容
settings.Encoding = new UTF8Encoding( false );
//設置換行符
settings.NewLineChars = Environment.NewLine;
|
完整的代碼示例如下:
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
//註意這兒不能直接用Encoding.UTF8如果用Encoding.UTF8將在輸出文本的最前面添加4個位元組的非xml內容
settings.Encoding = new UTF8Encoding( false );
//設置換行符
settings.NewLineChars = Environment.NewLine;
using (XmlWriter xmlWriter = XmlWriter.Create(ms, settings))
{
//寫xml文件開始<?xml version="1.0" encoding="utf-8" ?>
xmlWriter.WriteStartDocument( false );
//寫根節點
xmlWriter.WriteStartElement( "root" );
//寫位元組點
xmlWriter.WriteStartElement( "cat" );
//給節點添加屬性
xmlWriter.WriteAttributeString( "color" , "white" );
//給節點內部添加文本
xmlWriter.WriteString( "I'm a cat" );
xmlWriter.WriteEndElement();
//通過WriteElementString可以添加一個節點同時添加節點內容
xmlWriter.WriteElementString( "pig" , "pig is great" );
xmlWriter.WriteStartElement( "dog" );
//寫CData
xmlWriter.WriteCData( "<strong>dog is dog</strong>" );
xmlWriter.WriteEndElement();
xmlWriter.WriteComment( "this is an example writed by http://www.baidu.com/" );
xmlWriter.WriteEndElement();
xmlWriter.WriteEndDocument();
}
//將xml內容輸出到控制臺中
string xml = Encoding.UTF8.GetString(ms.ToArray());
Console.WriteLine(xml);
}
Console.Read();
}
}
}
|
C#處理Xml的相關隨筆:
1.通過XmlDocument讀寫Xml文檔 2.使用XmlReader讀Xml,使用XmlWriter寫Xml 3.使用Linq to xml存取XML 4.通過XmlScheme定義固定格式xml文檔 5.Xml序列化或者反序列化類 6.通過XPath查找Xml節點 7.通過Xslt轉化Xml格式