Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 223
Joan Venge Avatar asked Feb 03 '23 21:02

Joan Venge


1 Answers

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.
like image 127
John Saunders Avatar answered Feb 05 '23 09:02

John Saunders