Format an XML string

0

I usually do the following:

XmlDocument document = new XmlDocument();
document.LoadXml("htts://example.com/documento.xml");
File.WriteAllText(@"C:\ruta\mixml.xml", document.OuterXml);

and when opening the file, the result is that I get the xml in a single line:

<?xml version="1.0" encoding="utf-8"?><item><data><url>url01</url><files><file>file01</file><file>file02</file></files></data></item>

There are no spaces between lines, making it difficult to read when dealing with very long documents.

Using Json.NET there is an option to format a json with Formatting.Indented

string json = JsonConvert.SerializeObject(object, Formatting.Indented);

Is there an option to format an XML Indentation?

<?xml version="1.0" encoding="utf-8"?>
<item>
  <data>
    <url>url01</url>
    <files>
      <file>file01</file>
      <file>file02</file>
    </files>
  </data>
</item>
    
asked by iuninefrendor 09.12.2018 в 04:50
source

1 answer

1

Good morning mate, I told you that the solution is in the community in English, you were very close with the Formatting.Indented , the link:

Format XML String to Print Friendly XML String

The code that will most help you with the answers within the link:

You will have to analyze the content in some way ... I find that using LINQ is the easiest way to do it. Once again, everything depends on your exact scenario. Here is a working example that LINQ uses to format an input XML string.

string FormatXml(string xml){
     try{
         XDocument doc = XDocument.Parse(xml);
         return doc.ToString();
     }catch (Exception){
         // Maneja y muestra si hay alguna excepción fatal acá
         return xml;
     }
 }
  

Credits: Charles Prakash Dasari

I only ask you please, that we look for a little more, at the beginning it costs a bit, and afterwards you know how to look better. Any additional to the order

Best regards.

    
answered by 09.12.2018 / 14:54
source