C# XmlWriter

來源:互聯網
上載者:User

XmlWriter的工作方式類似於XmlReader,但順序相反。使用字串串連來快速建立Xml文檔和xml片段是非常迷人的,但我們應抵制這種誘惑。Xml是InfoSet的表示,不是角括弧。如果適用StringBuilder把字串字面串連在一起來建立xml,就把InfoSet降低為格式實現細節。記住xml文檔不是字串。XmlWriter還有一個設定類XmlWriterSettings。這個類包含縮排、換行、編碼、xml一致層級的選項。
 Double price = 49.99;
            DateTime publicationdate = new DateTime(2005, 1, 1);
            String isbn = "1-057-610-0";
            Author a = new Author();
            a.FirstName = "Scott";
            a.LastName = "Hanselman";

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.NewLineOnAttributes = true;

            Response.ContentType = "text/xml";

            XmlSerializerFactory factory = new XmlSerializerFactory();

            using (XmlWriter writer =XmlWriter.Create(Response.OutputStream, settings))
            {
                //Note the artificial, but useful, indenting
                writer.WriteStartDocument();
                writer.WriteStartElement("bookstore");
                writer.WriteStartElement("book");
                writer.WriteStartAttribute("publicationdate");
                writer.WriteValue(publicationdate);
                writer.WriteEndAttribute();
                writer.WriteStartAttribute("ISBN");
                writer.WriteValue(isbn);
                writer.WriteEndAttribute();
                writer.WriteElementString("title", "ASP.NET 2.0");
                writer.WriteStartElement("price");
                writer.WriteValue(price);
                writer.WriteEndElement(); //price
                XmlSerializer xs = factory.CreateSerializer(typeof(Author));
                xs.Serialize(writer, a);
                writer.WriteEndElement(); //book
                writer.WriteEndElement(); //bookstore
                writer.WriteEndDocument();
Linq for xml它不如XmlWriter快,但仍非常快,且非常容易閱讀。
  Double price = 49.99;
            DateTime publicationdate = new DateTime(2005, 1, 1);
            String isbn = "1-057-610-0";
            Author a = new Author();
            a.FirstName = "Scott";
            a.LastName = "Hanselman";

            Response.ContentType = "text/xml";
            XNamespace ns = "http://example.books.com";
            XDocument books = new XDocument(
                new XElement(ns + "bookstore",
                    new XElement(ns + "book",
                        new XAttribute("publicationdate", publicationdate),
                        new XAttribute("ISBN", isbn),
                        new XElement(ns + "title", "ASP.NET 2.0 Book"),
                        new XElement(ns + "price", price),
                        new XElement(ns + "author",
                            new XElement(ns + "first-name", a.FirstName),
                            new XElement(ns + "last-name", a.LastName)
                            )
                        )
                   )
                );
            Response.Write(books);
XPathDocument在記憶體中的資料結構上使用Xpath運算式的最高效方式,它實現了XPathNavigable介面,通過提供XPathNavigator,可以迭代底層的xml。XPathNavigator對xml進行隨機訪問。XPathDocument是唯讀,XmlDocument允許讀寫。
  //Load document
            string booksFile = Server.MapPath("books.xml");

            XPathDocument document = new XPathDocument(booksFile);
            XPathNavigator nav = document.CreateNavigator();

            //Add a namespace prefix that can be used in the XPath expression
            XmlNamespaceManager namespaceMgr = new XmlNamespaceManager(nav.NameTable);
            namespaceMgr.AddNamespace("b", "http://example.books.com");

            //All books whose price is not greater than 10.00
            foreach (XPathNavigator node in
                nav.Select("//b:book[not(b:price[. > 10.00])]/b:price",
                namespaceMgr))
            {
                Decimal price = (decimal)node.ValueAs(typeof(decimal));
                Response.Write(String.Format("Price is {0}<BR/>",
                    price));
            }
如果要以XPathNavigator的形式修改底層的xml節點,就應該使用XmlDocument代替XPathDocument。Xpath運算式的而計算比較慢,但應該可以編輯。在大多數情況下,應盡多的使用唯讀XPathDocument。
 //Load document
        string booksFile = Server.MapPath("books.xml");

        XmlDocument document = new XmlDocument();
        document.Load(booksFile);
        XPathNavigator nav = document.CreateNavigator();

        //Add a namespace prefix that can be used in the XPath expression
        XmlNamespaceManager namespaceMgr = new XmlNamespaceManager(nav.NameTable);
        namespaceMgr.AddNamespace("b", "http://example.books.com");

        //All books whose price is not greater than 10.00
        foreach (XPathNavigator node in
            nav.Select("//b:book[not(b:price[. > 10.00])]/b:price",
            namespaceMgr))
        {
            Decimal price = (decimal)node.ValueAs(typeof(decimal));
            node.SetTypedValue(price * 1.2M);
            Response.Write(String.Format("Price raised from {0} to {1}<BR/>",
                price,
                node.ValueAs(typeof(decimal))));
        }
以下是Linq的而用法
  //Load document
        string booksFile = Server.MapPath("books.xml");
        XDocument document = XDocument.Load(booksFile);

        //Add a namespace prefix that can be used in the XPath expression.
        // Note the need for a NameTable. It could be new or come from elsewhere.
        XmlNamespaceManager namespaceMgr = new XmlNamespaceManager(new NameTable());
        namespaceMgr.AddNamespace("b", "http://example.books.com");

        var nodes = document.XPathSelectElements("//b:book[not(b:price[. > 10.00])]/b:price",namespaceMgr);

        //All books whose price is not greater than 10.00
        foreach (var node in nodes)
        {
            Response.Write(node.Value + "<BR/>");
        }

關於Author的定義和books.xml檔案可以在http://blog.csdn.net/dz45693/archive/2010/05/06/5564617.aspx找到

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.