SilverLight学习笔记--XML操作

XML操作

XMLWriter 内容保存至客户端

修改 page.xaml 文件

        <TextBlock x:Name ="OutputTextBlock" Canvas.Top ="10" TextWrapping="Wrap"/>

在应用程序的 page.xaml.cs源文件中,添加下面的 using 语句:

sing System.Xml;

using System.IO;

using System.Text;

using System.IO.IsolatedStorage;

 

全部代码:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

using System.Xml;

using System.IO;

using System.Text;

using System.IO.IsolatedStorage;

 

 

 

namespace SilverlightApplication7

{

    public partial class Page : UserControl

    {

        public Page()

        {

            InitializeComponent();

 

            using (IsolatedStorageFile isoStore =

    IsolatedStorageFile.GetUserStoreForApplication())

            {

 

                // Create new file

                using (IsolatedStorageFileStream isoStream =

                    new IsolatedStorageFileStream("IsoStoreFile.xml",

                        FileMode.Create, isoStore))

                {

                    // Write to the Isolated Storage for the user.

                    XmlWriterSettings settings = new XmlWriterSettings();

                    settings.Indent = true;

                    // Create an XmlWriter.

                    using (XmlWriter writer = XmlWriter.Create(isoStream, settings))

                    {

 

                        writer.WriteComment("sample XML document");

 

                        // Write an element (this one is the root).

                        writer.WriteStartElement("book");

 

                        // Write the namespace declaration.

                        writer.WriteAttributeString("xmlns", "bk", null, "urn:samples");

 

                        // Write the genre attribute.

                        writer.WriteAttributeString("genre", "novel");

 

                        // Write the title.

                        writer.WriteStartElement("title");

                        writer.WriteString("The Handmaid's Tale");

                        writer.WriteEndElement();

 

                        // Write the price.

                        writer.WriteElementString("price", "19.95");

 

                        writer.WriteStartElement(null, "ISBN", "urn:samples");

                        writer.WriteString("1-861003-78");

                        writer.WriteEndElement();

 

                        // Write the style element (shows a different way to handle prefixes).

                        writer.WriteElementString("style", "urn:samples", "hardcover");

 

                        // Write the close tag for the root element.

                        writer.WriteEndElement();

 

                        // Write the XML to the file.

                        writer.Flush();

                    }

                }

                // Open the file again for reading.

                using (StreamReader reader =

                                new StreamReader(isoStore.OpenFile("IsoStoreFile.xml", FileMode.Open)))

                {

                    OutputTextBlock.Text = reader.ReadToEnd();

                }

 

 

                // Delete the IsoStoreFile.xml file.

                //isoStore.DeleteFile("IsoStoreFile.xml");

            }

 

 

        }

    }

}

使用 XmlReader 分析 XML

            StringBuilder output = new StringBuilder();

 

            String xmlString =

                    @"<?xml version='1.0'?>

        <!-- This is a sample XML document -->

        <Items>

          <Item>test with a child element <more/> stuff</Item>

        </Items>";

            // Create an XmlReader

            using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))

            {

                XmlWriterSettings ws = new XmlWriterSettings();

                ws.Indent = true;

                using (XmlWriter writer = XmlWriter.Create(output, ws))

                {

 

                    // Parse the file and display each of the nodes.

                    while (reader.Read())

                    {

                        switch (reader.NodeType)

                        {

                            case XmlNodeType.Element:

                                writer.WriteStartElement(reader.Name);

                                break;

                            case XmlNodeType.Text:

                                writer.WriteString(reader.Value);

                                break;

                            case XmlNodeType.XmlDeclaration:

                            case XmlNodeType.ProcessingInstruction:

                                writer.WriteProcessingInstruction(reader.Name, reader.Value);

                                break;

                            case XmlNodeType.Comment:

                                writer.WriteComment(reader.Value);

                                break;

                            case XmlNodeType.EndElement:

                                writer.WriteFullEndElement();

                                break;

                        }

                    }

 

                }

            }

            OutputTextBlock.Text = output.ToString();

 

使用 XmlReader 方法读取元素和属性的内容

            StringBuilder output = new StringBuilder();

 

            String xmlString =

                @"<bookstore>

        <book genre='autobiography' publicationdate='1981-03-22' ISBN='1-861003-11-0'>

            <title>The Autobiography of Benjamin Franklin</title>

            <author>

                <first-name>Benjamin</first-name>

                <last-name>Franklin</last-name>

            </author>

            <price>8.99</price>

        </book>

    </bookstore>";

 

            // Create an XmlReader

            using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))

            {

                reader.ReadToFollowing("book");

                reader.MoveToFirstAttribute();

                string genre = reader.Value;

                output.AppendLine("The genre value: " + genre);

 

                reader.ReadToFollowing("title");

                output.AppendLine("Content of the title element: " + reader.ReadElementContentAsString());

            }

 

            OutputTextBlock.Text = output.ToString();

 

 

LINQ to XML 创建动态 XAML

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

using System.Windows.Markup;

using System.Xml;

using System.Xml.Linq;

using System.IO;

using System.Text;

 

namespace SilverlightApplication7

{

    public partial class Page : UserControl

    {

       public Page()

        {

            InitializeComponent();

 

            XElement contacts =

        new XElement("Contacts",

            new XElement("Contact1",

             new XAttribute("Att1", 1),

              new XElement("Name", "Patrick Hines"),

                new XElement("Phone", "206-555-0144"),

                new XElement("Address",

                    new XElement("Street1", "123 Main St"),

                    new XElement("City", "Mercer Island"),

                    new XElement("State", "WA"),

                    new XElement("Postal", "68042")

                )

            ),

            new XElement("Contact2",

                new XElement("Name", "Yoshi Latime"),

                new XElement("Phone", "503-555-6874"),

                new XElement("Address",

                    new XElement("Street1", "City Center Plaza 516 Main St."),

                    new XElement("City", "Elgin"),

                    new XElement("State", "OR"),

                    new XElement("Postal", "97827")

                )

            )

        );

 

    // Create the first TextBlock control.

    // Note that the element has to declare two XAML namespaces.

    XElement textBlock1 = XElement.Parse(

            @"<TextBlock

xmlns='http://schemas.microsoft.com/client/2007'

xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'

TextWrapping= 'Wrap'

Width = '400'

Canvas.Top = '10'

Text=''/>");

 

    // Get the first child element from contacts xml tree.

    XElement contact1 = contacts.Element("Contact1");

 

    // Set the value of the last attribute "Text"

    // to the content of contacts xml tree.

    textBlock1.LastAttribute.SetValue(contact1.ToString());

 

 

    // Get the second child element from contacts xml tree.

    XElement contact2 = contacts.Element("Contact2");

 

    // Create the second TextBlock control.

    // Note that the element has to declare two XAML namespaces.

    XNamespace xmlns = "http://schemas.microsoft.com/client/2007";

    XElement textBlock2 = new XElement(xmlns + "TextBlock",

        new XAttribute(XNamespace.Xmlns + "x", "http://schemas.microsoft.com/winfx/2006/xaml"),

        new XAttribute("Canvas.Top", 250),

        new XAttribute("Width", "600"),

        new XAttribute("Text", contact2.ToString())

        );

 

 

 

    // Add TextBlock control to the page

    LayoutRoot.Children.Add(XamlReader.Load(textBlock1.ToString()) as UIElement);

    // Add TextBlock control to the page

    LayoutRoot.Children.Add(XamlReader.Load(textBlock2.ToString()) as UIElement);

 

            }

 

 

        }

    }

 

 

 

LINQ to XML 从任意 URI 位置加载 XML

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

using System.Windows.Markup;

using System.Xml;

using System.Xml.Linq;

using System.IO;

using System.Text;

 

namespace SilverlightApplication7

{

    public partial class Page : UserControl

    {

        public Page()

        {

            InitializeComponent();

 

            WebClient wc = new WebClient();

            wc.OpenReadCompleted += wc_OpenReadCompleted;

            wc.OpenReadAsync(new Uri("http://localhost/GetXML.aspx"));

 

 

        }

 

        private void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)

        {

            if (e.Error != null)

            {

                OutputTextBlock.Text = e.Error.Message;

                return;

            }

            using (Stream s = e.Result)

            {

                XDocument doc = XDocument.Load(s);

                OutputTextBlock.Text = doc.ToString(SaveOptions.OmitDuplicateNamespaces);

            }

        }    

    }

}

 

LINQ to XML 保存到本地

            XDocument doc = new XDocument(

                    new XComment("This is a comment"),

                    new XElement("Root",

                        new XElement("Child1", "data1"),

                        new XElement("Child2", "data2")

                    )

                );

 

            using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())

            {

                using (IsolatedStorageFileStream isoStream =

                    new IsolatedStorageFileStream("myFile.xml", FileMode.Create, isoStore))

                {

                    doc.Save(isoStream);

                }

            }

 

            using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())

            {

                using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("myFile.xml", FileMode.Open, isoStore))

                {

                    XDocument doc1 = XDocument.Load(isoStream);

                    OutputTextBlock.Text = doc1.ToString();

                }

            }

 

XAP 包加载文件

创建 book.xml 文件,然后将其添加到您的项目中。这样还会将它添加到应用程序的 XAP 包中。确保将 book.xml 文件的 Build Action 属性设置为 Content.

<?xml version="1.0" encoding="utf-8" ?>

<bookstore>

 <book genre='novel' ISBN='10-861003-324'>

    <title>The Handmaid's Tale</title>

    <price>19.95</price>

 </book>

 <book genre='novel' ISBN='1-861001-57-5'>

    <title>Pride And Prejudice</title>

    <price>24.95</price>

 </book>

</bookstore>

 

自应用程序的 XAP 文件加载 XML 文件。然后使用 ReadInnerXml ReadOuterXml 方法读取元素内容。

 

            StringBuilder output = new StringBuilder();

 

            // XmlXapResolver is the default resolver.

            using (XmlReader reader = XmlReader.Create("book.xml"))

            {

                // Moves the reader to the root element.

                reader.MoveToContent();

 

                reader.ReadToFollowing("book");

                // Note that ReadInnerXml only returns the markup of the node's children

                // so the book's attributes are not returned.

                output.AppendLine("Read the first book using ReadInnerXml...");

                output.AppendLine(reader.ReadInnerXml());

 

                reader.ReadToFollowing("book");

 

                // ReadOuterXml returns the markup for the current node and its children

                // so the book's attributes are also returned.

                output.AppendLine("Read the second book using ReadOuterXml...");

                output.AppendLine(reader.ReadOuterXml());

 

            }

 

            OutputTextBlock.Text = output.ToString();

 

你可能感兴趣的:(silverlight)