Search code examples
c#xmlxmlreader

Parsing XML data from a string


What I want to do is grab the xml data from a string not a txt file. This works:

// xmlData.txt contains < m t='Hello' u='1337' />

XmlReader config = new XmlTextReader("../../xmldata.txt");
config.Read();
Console.WriteLine("Data: " + config.GetAttribute("t"));

But I want to parse it from a string not a document.

How do I parse XML data from a string?


Solution

  • Use a StringReader and feed it to the XmlTextReader:

    StringReader sr = new StringReader("<m t='Hello' u='1337'/>");
    XmlReader config = new XmlTextReader(sr);
    config.Read();
    Console.WriteLine("Data: " + config.GetAttribute("t"));