Joan Venge
Joan Venge

Reputation: 330992

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

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?

Upvotes: 10

Views: 15427

Answers (2)

Alexei Levenkov
Alexei Levenkov

Reputation: 100547

XElement.ReadFrom(XmlReader.Create(fileName))

But explicitly managing file stream objects and XmlReader objects is better - you know when streams are closed...

Upvotes: 4

John Saunders
John Saunders

Reputation: 161773

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.

Upvotes: 11

Related Questions