Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you create an indented XML string from an XDocument in c#?

Tags:

I have an XDocument object and the ToString() method returns XML without any indentation. How do I create a string from this containing indented XML?

edit: I'm asking how to create an in memory string rather than writing out to a file.

edit: Looks like I accidentally asked a trick question here... ToString() does return indented XML.

like image 458
JC. Avatar asked Mar 03 '10 20:03

JC.


People also ask

How do you add an indent in XML?

You can trigger a format and indent operation for your XML document (in Text mode) using one of the following actions: Format and Indent toolbar button - Formats and indents the current document. Document > Source > Format and Indent - Formats and indents the whole document.

Should I use XDocument or XmlDocument?

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 C#?

The XDocument class contains the information necessary for a valid XML document, which includes an XML declaration, processing instructions, and comments. You only have to create XDocument objects if you require the specific functionality provided by the XDocument class.


1 Answers

XDocument doc = XDocument.Parse(xmlString); string indented = doc.ToString(); 
like image 71
John Saunders Avatar answered Sep 27 '22 17:09

John Saunders