从Silverlight中包含xml的字符串中提取值

时间:2010-02-24 13:53:16

标签: xml silverlight

string xmlText= "
                  <Person>
                     <Name>abc</Name>
                     <Age>22</Age>
                  </person>";

我想要值abc和22 m使用silverlight 4和XmlTextReader不可用。

1 个答案:

答案 0 :(得分:1)

您可以使用LINQ to XML或XmlReader在Silverlight中解析XML数据。

这是一些使用XmlReader的示例代码。它非常简单,只有 可以使用您定义的确切输入字符串。但是,它应该足以让你继续前进。

string xmlText= @"
                  <Person>
                    <Name>abc</Name>
                      <Age>22</Age>
                  </Person>";
// Create an XmlReader
using (XmlReader reader = XmlReader.Create(new StringReader(xmlText)))
{
  // Parse the file and display each of the nodes.
  while (reader.Read())
  {
    if (reader.Name == "Name" && reader.NodeType == XmlNodeType.Element)
    {
      // Advace to the element's text node
      reader.Read();
      // ... do what you want (you can get the value with reader.Value)
    }
    else if (reader.Name == "Age" && reader.NodeType == XmlNodeType.Element)
    {
      // Advace to the element's text node
      reader.Read();
      // ... do what you want (you can get the value with reader.Value)
    }
}

这是一篇包含更多细节的文章:

http://msdn.microsoft.com/en-us/library/cc188996(VS.95).aspx