Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate XDocument from String

I'm working on a little something and I am trying to figure out whether I can load an XDocument from a string. XDocument.Load() seems to take the string passed to it as a path to a physical XML file.

I want to try and bypass the step of first having to create the physical XML file and jump straight to populating the XDocument.

Any ideas?

like image 933
StevenMcD Avatar asked Apr 14 '09 13:04

StevenMcD


People also ask

How to create XDocument from string in c#?

TextReader tr = new StringReader("<Root>Content</Root>"); XDocument doc = XDocument. Load(tr); Console. WriteLine(doc); This was taken from the MSDN docs for XDocument.

How do I load XML in XDocument?

One possible use for this method is to create a copy of a DOM document in a LINQ to XML tree. To do this, you create an XmlNodeReader from a DOM document, and then use the XmlNodeReader to create an XDocument. LINQ to XML's loading functionality is built upon XmlReader.

What is the difference between XmlDocument and XDocument?

XDocument is from the LINQ to XML API, and XmlDocument is the standard DOM-style API for XML. If you know DOM well, and don't want to learn LINQ to XML, go with XmlDocument . If you're new to both, check out this page that compares the two, and pick which one you like the looks of better.

What is XDocument parse?

Parse(String) Creates a new XDocument from a string. Parse(String, LoadOptions) Creates a new XDocument from a string, optionally preserving white space, setting the base URI, and retaining line information.


4 Answers

You can use XDocument.Parse for this.

like image 167
Ronald Wildenberg Avatar answered Oct 19 '22 06:10

Ronald Wildenberg


You can use XDocument.Parse(string) instead of Load(string).

like image 37
Samuel Avatar answered Oct 19 '22 07:10

Samuel


How about this...?

TextReader tr = new StringReader("<Root>Content</Root>");
XDocument doc = XDocument.Load(tr);
Console.WriteLine(doc);

This was taken from the MSDN docs for XDocument.Load, found here...

http://msdn.microsoft.com/en-us/library/bb299692.aspx

like image 42
Martin Peck Avatar answered Oct 19 '22 05:10

Martin Peck


Try the Parse method.

like image 24
bruno conde Avatar answered Oct 19 '22 05:10

bruno conde