2

I want to load my xml file in my app and read just specific tags from my xml. Can someone help me? I have tried couple of things but all I get is the full xml text, not the specific tags.

This is the code:

 try
 {
     StorageFolder storageFolder = Package.Current.InstalledLocation;
     StorageFile storageFile = await storageFolder.GetFileAsync("players2.xml");

     XmlTextBlock.Text = await FileIO.ReadTextAsync(storageFile, Windows.Storage.Streams.UnicodeEncoding.Utf8);
 }
 catch (Exception ex)
 {
     XmlTextBlock.Text = ex.Message;
 }

and my xml is:

<player>
<name>Ricardo Ferreira Rodrigues</name>
<shirtnumber>1</shirtnumber>
</player>

I want to see the results in txtname and txtshirtnumber. Someone can help?

chue x
  • 18,573
  • 7
  • 56
  • 70
ricardo_r
  • 39
  • 1
  • 9

2 Answers2

2

As Jon commented, you should read about LINQ to XML. It's the best (easiest and most powerful) way to handle XML structures in .NET.

Your document is quite simple, so the queries are simple too:

// parse the xml into XDocument instance
var doc = XDocument.Parse(XmlTextBlock.Text);

// query for <name> and <shirtnumber> and assign values to proper textboxes
txtname.Text = (string)doc.Root.Element("name");
txtshirtnumber.Text = (string)doc.Root.Element("shirtnumber");
chue x
  • 18,573
  • 7
  • 56
  • 70
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
2

If it were me, I would deserialize the XML directly into a class.

How to Deserialize XML document

string path = "file.xml";
StreamReader reader = new StreamReader(path);

XmlSerializer serializer = new XmlSerializer(typeof(MyClass));
var x = (MyClass)serializer.Deserialize(reader);

reader.Close();

C# XML Serialization/Deserialization

[XmlRoot("Document", Namespace = "")]
public partial class MyClass
{
    [XmlAttribute("Id")]
    public string Id { get; set; }

    [XmlElement("Name")]
    public string Name { get; set; }
}

How to de-serialize XML with many child nodes

http://www.stepupframeworks.com/Home/products/xml-object-mapping-xom/

Community
  • 1
  • 1
Jerry Nixon
  • 31,313
  • 14
  • 117
  • 233