Search code examples
perlmojolicious

mojolicious auto-indent XML/HTML


Can a Mojo tool auto-indent a string such the xml below?

<rpc-reply message-id="101" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"><data><native xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-native"><version>17.1</version><hostname>R1</hostname></native></data></rpc-reply>

I have looked through the assocated Mojo packages, however, i cannot find this option.

Thanks


Solution

  • Not with Mojolicious directly (or any Mojo::* modules I could find) however I know at least that XML::Twig comes with the xml_pp executable.

    Extracting the most basic code from that script gives you this...

    use XML::Twig;
    
    my $str = '<rpc-reply message-id="101" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"><data><native xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-native"><version>17.1</version><hostname>R1</hostname></native></ data></rpc-reply>';
    
    my $xt = XML::Twig->new(pretty_print => 'indented');
    
    my $indented = $xt->parse($str)->sprint;
    
    print $indented
    

    Which outputs this...

    <rpc-reply message-id="101" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
      <data>
        <native xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-native">
          <version>17.1</version>
          <hostname>R1</hostname>
        </native>
      </data>
    </rpc-reply>
    

    Then you can output the string however you like.