Question

Quelqu'un a-t-il une fonction clé en main qui prend une chaîne XML et renvoie une chaîne correctement indentée?

par exemple

<XML><TAG1>A</TAG1><TAG2><Tag3></Tag3></TAG2></XML>

et renverra la chaîne correctement formatée après avoir inséré des sauts de ligne, des tabulations ou des espaces?

Était-ce utile?

La solution

La RTL a un FormatXMLData dans XMLDoc.pas accepté et retourne des chaînes.

Autres conseils

Utilisation de OmniXML :

program TestIndentXML;

{$APPTYPE CONSOLE}

uses
  SysUtils,
  OmniXML,
  OmniXMLUtils;

function IndentXML(const xml: string): string;
var
  xmlDoc: IXMLDocument;
begin
  Result := '';
  xmlDoc := CreateXMLDoc;
  if not XMLLoadFromAnsiString(xmlDoc, xml) then
    Exit;
  Result := XMLSaveToAnsiString(xmlDoc, ofIndent);
end;

begin
  Writeln(IndentXML('<XML><TAG1>A</TAG1><TAG2><Tag3></Tag3></TAG2></XML>'));
  Readln;
end.

Le fragment de code ci-dessus est publié dans le domaine public.

Utilisation de XSLT ...

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="xml" indent="yes" />
    <xsl:template match="/">
        <xsl:copy-of select="."/>
    </xsl:template>
</xsl:stylesheet>

J'ai utilisé Ranger avec libtidy de Michael Elsd & # 246; rfer. Il vous donne des tas d'options et vous pouvez les configurer en externe à l'application. Également applicable au HTML.

C’est un code très approximatif que j’ai utilisé. Faites-le comme bon vous semble.

function TForm1.DoTidy(const Source: string): string;
var
  Tidy              : TLibTidy;
begin
  if not TidyGlobal.LoadTidyLibrary('libtidy.dll') then
  begin
    //    Application.MessageBox('TidyLib is not available.', 'Error', 16);
    //    exit;
    raise Exception.Create('Cannot load TidyLib.dll');
  end;
  Tidy := TLibTidy.Create(Self);
  try
    Tidy.LoadConfigFile(ExtractFilePath(Application.ExeName) +
      'tidyconfig.txt');
    //    Tidy.Configuration.IndentContent := tsYes;
    //    Tidy.Configuration.IndentSpaces := 5;
    //    Tidy.Configuration.UpperCaseTags := False;
    //    Tidy.Configuration.NumEntities := True;
    //    Tidy.Configuration.AccessibilityCheckLevel := 2;
    //    Tidy.Configuration.InlineTags := 'foo,bar';
    //    Tidy.Configuration.XmlDecl := True;
    //    Tidy.Configuration.XmlTags := True;
    //    Tidy.Configuration.CharEncoding := TidyUTF8;
    //    Tidy.Configuration.WrapLen := 0;
    //    Tidy.SaveConfigFile('tidyconfig.txt');
    Tidy.ParseString(Source);
    Result := Tidy.RunDiagnosticsAndRepair;
  finally
    Tidy.Free;
  end;
end;

L'objet DOM Document XML créé dans Delphi dispose d'une jolie option de formatage. Il vous suffit de charger votre code XML dans celui-ci et de le sauvegarder à nouveau. Si cette option est définie, cela rend tout cela joli.

Je vais chercher et mettre à jour cette réponse.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top