【笔记】【LINQ编程技术内幕】第二十一章 使用XmlWriter生成XML

    技术2026-04-12  8

    快速浏览XmlWriter

    XmlWriter类是一个抽象类。这意味着你可以声明它但却不能将其实例化。跟准确地说,赋值运算符的左侧可以是一个XmlWriter,而赋值运算符的右侧必须是它的一个具体后代。 XmlWriter的基本行为是这样的:它含有用于向XML文档中写入元素的方法(并具有很好的格式化效果),不过并不会强制生成一个正确的XML文档。 XmlWriter将二进制数据编码为Base64数据或十六进制值。可以完成的操作主要有:指定是否支持名称空间、刷新和关闭文档、获取当前命名空间、编写有效名称和平镇。XmlWriter不会检测无效元素或属性、不匹配指定编码的字符、重复字符等。也就是说,使用XmlWriter的派生类将使你能够编写出一个不那么严格的XML。 XmlWriter所支持的元素有CDATA元素、处理指令、元素和属性。这些功能都有着象映的名称。

    使用XmlTextWriter编写XML文件

    class Program { static void Main(string[] args) { string all = GetQuotes("MSFT GOOG DELL"); string[] quotes = all.Replace("<b>", "").Replace("</b>", "").Replace("\"", "").Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); using (XmlTextWriter writer = new XmlTextWriter("quotes.xml", System.Text.Encoding.UTF8)) { writer.WriteStartDocument(true); writer.WriteStartElement("Root", ""); foreach (string str in quotes) { string[] fields = str.Split(new char[] { ',', '-' }, StringSplitOptions.RemoveEmptyEntries); writer.WriteStartElement("Company"); writer.WriteValue(fields[0].Trim()); writer.WriteStartElement("LastPrice"); writer.WriteAttributeString("Time", fields[1].Trim()); writer.WriteValue(fields[2].Trim()); writer.WriteEndElement(); writer.WriteElementString("HighToday", fields[3].Trim()); writer.WriteEndElement(); } writer.WriteEndElement(); writer.WriteEndDocument(); writer.Close(); } } static string GetQuotes(string stocks) { string url = @"http://quote.yahoo.com/d/quotes.csv?s={0}&f=nlh"; HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(string.Format(url, stocks)); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII)) { try { return reader.ReadToEnd(); } finally { // don't need to close the reader because Dispose does response.Close(); } } } }
    Processed: 0.014, SQL: 9