Silverlight读取XML

XMLReader与XMLWriter都没有学会,暂时使用XDocument加Linq读取。
ExpandedBlockStart.gif 大气象
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.Xml.Linq;
using  System.Text;
using  System.IO;

namespace  HCLoad
{
    
public   partial   class  UC_Test : UserControl
    {
        
public  UC_Test()
        {
            InitializeComponent();
        }
        
// Linq实体类
         public   class  project
        {
            
public   int  id {  get set ; }
        }
        
private   void  GetXmlFromString()
        {
            
string  strXml  =  
            
@" <?xml version=""1.0"" encoding=""utf-16"" ?>
            <projects>
                <project id=""1""></project>
                <project id=""2""></project>
            </projects>
" ;

            TextReader txtReader 
=   new  StringReader(strXml);

            XDocument xDoc 
=  XDocument.Load(txtReader);

            var projects 
=  from f  in  xDoc.Descendants( " project " )
                           select 
new  project
                           {
                               id 
=   int .Parse(f.Attribute( " id " ).Value)
                           };
            List
< project >  _projects  =   new  List < project > ();
            _projects.AddRange(projects);
            
// 遍历
             for  ( int  i  =   0 ; i  <  _projects.Count; i ++ )
            {
                MessageBox.Show(_projects[i].id.ToString());
            }
        }
        
private   void  Button_Click( object  sender, RoutedEventArgs e)
        {
            GetXmlFromString();
        }
    }
}

参考一:Silverlight读取xml

这例子是为我的试验项目"SLShowCase"做的读取xml的试验.看到园子里的朋友做到仿163幻灯片的demo就提前发上来了.
项目的功能是做案例展示.
ok  首先,先定义xml.
projects.xml

<? xml version="1.0" encoding="utf-8"  ?>
< projects >
  
< project  id ="1"  title ="nasa.wang @ cnblogs"  category ="web"  hit ="23"  createdate ="2008-4-9"  converpic ="null"  iscommend ="true"  votenum ="8"  score ="10" >
  
</ project >
</ projects >

在sl中定义类.

     public   class  project
    {
        
public   int  id {  get set ; }
        
public   string  title {  get set ; }
        
public   string  category {  get set ; }
        
public   int  hit {  get set ; }
        
public  DateTime createdate {  get set ; }
        
public   string  converpic {  get set ; }
        
public   bool  iscommend {  get set ; }
        
public   int  votenum {  get set ; }
        
public   int  score {  get set ; }
        
// public IList<pitem> pitems { get; set; }
        
// public IList<pcomment> pcomments { get; set; }
    }

使用WebClient来加载数据.linq来格式化数据.

         public  Page()
        {
            InitializeComponent();
            WebClient client 
=   new  WebClient();
            client.DownloadStringAsync(
new  Uri(HtmlPage.Document.DocumentUri,  " projects.xml " ));
            client.DownloadStringCompleted 
+=   new  DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
        }

        
void  client_DownloadStringCompleted( object  sender, DownloadStringCompletedEventArgs e)
        {
            XmlReader reader 
=  XmlReader.Create( new  StringReader(e.Result));
            XDocument document 
=  XDocument.Load(reader);
            var projects 
=  from f  in  document.Descendants( " project " )
                           select 
new  project
                           {
                               id 
=   int .Parse(f.Attribute( " id " ).Value),
                               title 
=  f.Attribute( " title " ).Value,
                               category 
=  f.Attribute( " category " ).Value,
                               hit 
=   int .Parse(f.Attribute( " hit " ).Value),
                               createdate 
=  DateTime.Parse(f.Attribute( " createdate " ).Value),
                               converpic 
=  f.Attribute( " converpic " ).Value,
                               iscommend 
=   bool .Parse(f.Attribute( " iscommend " ).Value),
                               votenum 
=   int .Parse(f.Attribute( " votenum " ).Value),
                               score 
=   int .Parse(f.Attribute( " score " ).Value),
                           };
            List
< project >  _projects  =   new  List < project > ();
            _projects.AddRange(projects);
            txtStatus.Text 
= " read success for  "   +  _projects[ 0 ].title;
        }


读取完毕.  ;)

代码下载:http://files.cnblogs.com/nasa/silverlight/readxmlfile.zip

 

参考二:http://msdn.microsoft.com/zh-cn/library/system.io.textreader(VS.80).aspx

using System;
using System.IO;

class TextRW
{
    static void Main()
    {
        TextWriter stringWriter = new StringWriter();
        using(TextWriter streamWriter = 
            new StreamWriter("InvalidPathChars.txt"))
        {
            WriteText(stringWriter);
            WriteText(streamWriter);
        }

        TextReader stringReader = 
            new StringReader(stringWriter.ToString());
        using(TextReader streamReader = 
            new StreamReader("InvalidPathChars.txt"))
        {
            ReadText(stringReader);
            ReadText(streamReader);
        }
    }

    static void WriteText(TextWriter textWriter)
    {
        textWriter.Write("Invalid file path characters are: ");
        textWriter.Write(Path.InvalidPathChars);
        textWriter.Write('.');
    }

    static void ReadText(TextReader textReader)
    {
        Console.WriteLine("From {0} - {1}", 
            textReader.GetType().Name, textReader.ReadToEnd());
    }
}


参考三:http://blog.csdn.net/dotfun/archive/2009/11/19/4829349.aspx
Silverlight 2使用C#遍历XML(兼容Silverlight3)

在Silverlight 1.1中,C#只能用XmlReader这样一个非常轻量级的东西来解析XML,因此稍有不慎就会出现很多非常奇怪的错误,在这里对XML的解析做一个简单的流程介绍吧。

在对流式XML的解析中,XmlReader对XML节点进行一些区分,这些节点的类型包括:

引用内容:
public enum XmlNodeType
{
    None = 0,
    Element = 1,
    Attribute = 2,
    Text = 3,
    CDATA = 4,
    EntityReference = 5,
    Entity = 6,
    ProcessingInstruction = 7,
    Comment = 8,
    Document = 9,
    DocumentType = 10,
    DocumentFragment = 11,
    Notation = 12,
    Whitespace = 13,
    SignificantWhitespace = 14,
    EndElement = 15,
    EndEntity = 16,
    XmlDeclaration = 17,
}

其中常用到的有Element、Attribite、Text、CDATA、EndElement等。其中Element类型的节点为“”形式,EndElement的的节点为“”形式,而Text类型则可以为一对标记之间的文本内容或者节点之间的空格、换行等。

了解了这些,我们再来看怎么从一个XML文件流中找出自己想要的数据。首先假设有一个这样的XML数据流,其XML结构如下:

引用内容:

 
   
    热门动漫
    OOboy.net
   
    Thu, 16 Aug 2007 09:39:19 GMT
 
 
   
    海外剧场
    OOboy.net
   
    Thu, 16 Aug 2007 09:39:19 GMT
 


我们用XmlReader的Create方法从这个Stream中创建了一个XmlReader对象,现在我们解析出想要的数据——item项目中的各个子项:Title、Catalog、Author、Email、Modified。

解析过程在下面代码的注释中:

引用内容:
//reader是一个XmlReader实例
//开始读取流,直到读完为止
//reader.Read()每次读取一个XML节点(XML节点的描述在本文开头)
while (reader.Read())
{
    //如果该节点是一个开始节点,而且节点的名称叫做item
    //那么我们继续读取item子树
    if ((reader.IsStartElement()) && (reader.LocalName == "item"))
    {
        //创建一个新的Item对象,后面把数据保存到Item对象中
        Item item = new Item();

        //继续读取Item下面的内容
        using (XmlReader itemReader = reader.ReadSubtree())
        {
            //开始读取Item下面的内容,知道读完Item子树为止
            //当碰到节点时会跳出循环
            while (itemReader.Read())
            {
                //如果找到一个Element,我们就读取其中的值
                //用这种节点可以忽略空格、回车等等
                if (itemReader.NodeType == XmlNodeType.Element)
                {
                    //如果是空节点,比如上文中的这样的节点
                    //此时读取下一个节点,否则会出错
                    if (itemReader.IsEmptyElement)
                    {
                        continue;
                    }

                    //如果不是空节点
                    //把节点的name记录下来
                    string nodeName = itemReader.Name;

                    //读取节点内地文本节点
                    itemReader.Read();
                    if (itemReader.NodeType == XmlNodeType.Text)
                    {
                        //根据节点的name,把值保存到Item对应的属性中
                        switch (nodeName.ToUpper())
                        {
                            case "TITLE":
                                item.title = itemReader.Value;
                                break;
                            case "CATALOG":
                                item.catalog = itemReader.Value;
                                break;
                            case "AUTHOR":
                                item.author = itemReader.Value;
                                break;
                            case "EMAIL":
                                item.email = itemReader.Value;
                                break;
                            case "MODIFIED":
                                item.modified = itemReader.Value;
                                break;
                        }
                    }
                    //读取完成,再读结束节点End Element
                    itemReader.Read();
                }
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值