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

Now I am using:

XElement xe = XElement.ReadFrom 

which requires an XmlReader :

 XmlReader reader = XmlTextReader.Create 

which requires a string, and this requires passing a StringReader :

 new StringReader 

which requires TextReader/StreamReader to finally transfer the file path:

 TextReader textReader = new StreamReader ( file ); 

The easiest way to do this? I already have code that uses XElement , so it works fine, but I want to reduce the number of steps to get XElement from xml file. Something like:

 XElement xe = XElement.ReadFrom (string file); 

Any ideas?

+6
c # xmlreader xelement
source share
2 answers

Joan, use XDocument.Load (string) :

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

Some comments:

  • You should never use XmlTextReader.Create . use XmlReader.Create . This is a static method, so it doesn't matter which derived class you use to reference it. This is misleading to use XmlTextReader.Create , as it looks different from XmlReader.Create . This is not true.
  • XmlReader.Create has an overload that accepts a string, just like XDocument.Load does: XmlReader.Create(string inputUri) .
  • Actually there is no such thing as XElement.ReadFrom . This is actually XNode.ReadFrom .
+7
source share
 XElement.ReadFrom(XmlReader.Create(fileName)) 

But explicit management of file stream objects and XmlReader objects is better - you know when streams are closed ...

+4
source share

All Articles