200 votes

Formater une chaîne XML pour imprimer une chaîne XML conviviale

J'ai une chaîne XML en tant que telle:

 <?xml version='1.0'?><response><error code='1'> Success</error></response>
 

Il n'y a pas de lignes entre un élément et un autre, il est donc très difficile à lire. Je veux une fonction qui formate la chaîne ci-dessus:

 <?xml version='1.0'?>
<response>
<error code='1'> Success</error>
</response>
 

Sans avoir à écrire moi-même manuellement la fonction de formatage, existe-t-il une bibliothèque .Net ou un extrait de code que je peux utiliser sans aide?

341voto

Vous devrez analyser le contenu d'une manière ou d'une autre ... Je trouve que LINQ est le moyen le plus simple de le faire. Encore une fois, tout dépend de votre scénario exact. Voici un exemple de travail utilisant LINQ pour formater une chaîne XML d'entrée.

 string FormatXml(string xml)
{
     try
     {
         XDocument doc = XDocument.Parse(xml);
         return doc.ToString();
     }
     catch (Exception)
     {
         return xml;
     }
 }
 

[les instructions using sont omises pour des raisons de brièveté]

201voto

S M Kamran Points 1800

Utiliser XmlTextWriter ...

 public static String PrintXML(String XML)
{
String Result = "";

MemoryStream mStream = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(mStream, Encoding.Unicode);
XmlDocument document   = new XmlDocument();

try
{
	// Load the XmlDocument with the XML.
	document.LoadXml(XML);

	writer.Formatting = Formatting.Indented;

	// Write the XML into a formatting XmlTextWriter
	document.WriteContentTo(writer);
	writer.Flush();
	mStream.Flush();

	// Have to rewind the MemoryStream in order to read
	// its contents.
	mStream.Position = 0;

	// Read MemoryStream contents into a StreamReader.
	StreamReader sReader = new StreamReader(mStream);

	// Extract the text from the StreamReader.
	String FormattedXML = sReader.ReadToEnd();

	Result = FormattedXML;
}
catch (XmlException)
{
}

mStream.Close();
writer.Close();

return Result;
}
 

63voto

Todd Points 2386

Celui-ci, de kristopherjohnson, est beaucoup mieux:

  1. Il ne nécessite pas non plus d'en-tête de document XML.
  2. A des exceptions plus claires
  3. Ajoute des options de comportement supplémentaires: OmitXmlDeclaration = true, NewLineOnAttributes = true
  4. Moins de lignes de code

     static string PrettyXml(string xml)
    {
        var stringBuilder = new StringBuilder();
    
        var element = XElement.Parse(xml);
    
        var settings = new XmlWriterSettings();
        settings.OmitXmlDeclaration = true;
        settings.Indent = true;
        settings.NewLineOnAttributes = true;
    
        using (var xmlWriter = XmlWriter.Create(stringBuilder, settings))
        {
            element.Save(xmlWriter);
        }
    
        return stringBuilder.ToString();
    }
     

8voto

Chansik Im Points 1099

Vérifiez le lien suivant: Comment imprimer joliment XML (Malheureusement, le lien retourne maintenant 404 :()

La méthode dans le lien prend une chaîne XML en tant qu'argument et renvoie une chaîne XML bien formée (en retrait).

Je viens de copier l'exemple de code du lien pour rendre cette réponse plus complète et plus pratique.

 public static String PrettyPrint(String XML)
{
    String Result = "";

    MemoryStream MS = new MemoryStream();
    XmlTextWriter W = new XmlTextWriter(MS, Encoding.Unicode);
    XmlDocument D   = new XmlDocument();

    try
    {
        // Load the XmlDocument with the XML.
        D.LoadXml(XML);

        W.Formatting = Formatting.Indented;

        // Write the XML into a formatting XmlTextWriter
        D.WriteContentTo(W);
        W.Flush();
        MS.Flush();

        // Have to rewind the MemoryStream in order to read
        // its contents.
        MS.Position = 0;

        // Read MemoryStream contents into a StreamReader.
        StreamReader SR = new StreamReader(MS);

        // Extract the text from the StreamReader.
        String FormattedXML = SR.ReadToEnd();

        Result = FormattedXML;
    }
    catch (XmlException)
    {
    }

    MS.Close();
    W.Close();

    return Result;
}
 

1voto

CMS Points 315406

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X