How to read an xml file directly to get an XElement value?

Joan Venge picture Joan Venge · Feb 26, 2011 · Viewed 12.1k times · Source

Right now I am using:

XElement xe = XElement.ReadFrom

which requires an XmlReader:

XmlReader reader = XmlTextReader.Create

which requires a string, and that requires me to pass a StringReader:

new StringReader

which requires a TextReader/StreamReader to finally be able to pass the file path to it:

TextReader textReader = new StreamReader ( file );

Is the simpliest way to do this? I already have code that uses an XElement so it works fine but I want to cut down the number of steps to get the XElement from an xml file. Something like:

XElement xe = XElement.ReadFrom (string file);

Any ideas?

Answer

John Saunders picture John Saunders · Feb 26, 2011

Joan, use XDocument.Load(string):

XDocument doc = XDocument.Load("PurchaseOrder.xml");

Some comments:

  1. You should never use XmlTextReader.Create. use XmlReader.Create. It's a static method, so it doesn't make a difference which derived class you use to refer to it. It's misleading to use XmlTextReader.Create, since it looks like that's different from XmlReader.Create. It's not.
  2. XmlReader.Create has an overload that accepts a string, just like XDocument.Load does: XmlReader.Create(string inputUri).
  3. There's actually no such thing as XElement.ReadFrom. It's actually XNode.ReadFrom.