Domanda

Qualcuno ha una funzione pronta che accetta una stringa XML e restituisce una stringa correttamente rientrata?

es

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

e restituirà String ben formattato in cambio dopo aver inserito interruzioni di riga e schede o spazi?

È stato utile?

Soluzione

RTL ha FormatXMLData in XMLDoc.pas che accetta e restituisce stringhe.

Altri suggerimenti

Utilizzo di 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.

Il frammento di codice sopra è rilasciato al pubblico dominio.

Uso di 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>

Ho usato Tidy con libtidy di Michael Elsdörfer. Ti dà un sacco di opzioni e puoi configurarle esternamente all'applicazione. Applicabile anche a HTML.

Questo è un codice molto approssimativo che ho usato. Fallo come preferisci.

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'oggetto DOM documento XML incorporato in Delphi ha un'opzione di formattazione piuttosto. Devi solo caricare il tuo XML in esso e salvarlo nuovamente, e se hai quell'opzione impostata, lo rende tutto carino.

Lo cercherò e aggiornerò questa risposta.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top