Regex for indented XML file

Is it possible to write REGEX (replace search) that when launched on an XML line, an indented XML line will be output?

If so, then REGEX :)

+3
source share
7 answers

Is it possible to write REGEX (replace search), which when launched on an XML string [... all]

No.

Use an XML parser to read the string, and then an XML serializer to write it in "pretty mode."

Each XML processor has its own parameters, so it depends on the platform, but here is a somewhat lengthy method that works on DOM Level 3 LS-compliant implementations:

input= implementation.createLSInput();
input.stringData= unprettyxml;
parser= implementation.createLSParser(implementation.MODE_SYNCHRONOUS, null);
document= parser.parse(input);
serializer= implementation.createLSSerializer();
serializer.domConfig.setParameter("format-pretty-print", true);
prettyxml= serializer.writeToString(document);
+5
source

, . , .

XML, . ?

+5

, regex XML. , , ( ) .. regex . XML - XML, , XML .

?

+3

. . , perl 5.10 , . ... , CDATA, XML, .

DOM. , , DOM. , , , .

+3

voodoo regexp, , .
http://www.perlmonks.org/?node_id=261292
XML:: LibXMl , .

+2

, .

, , .

+1

:

  private static Regex indentingRegex=new Regex(@"\<\s*(?<tag>[\w\-]+)(\s+[\w\-]+\s*=\s*""[^""]*""|'[^']*')*\s*\>[^\<]*\<\s*/\s*\k<tag>\s*\>|\<[!\?]((?<=!)--((?!--\>).)*--\>|(""[^""]*""|'[^']'|[^>])*\>)|\<\s*(?<closing>/)?\s*[\w\-]+(\s+[\w\-]+\s*=\s*""[^""]*""|'[^']*')*\s*((/\s*)|(?<opening>))\>|[^\<]*", RegexOptions.ExplicitCapture|RegexOptions.Singleline);

  public static string IndentXml(string xml) {
        StringBuilder result=new StringBuilder(xml.Length*2);
        int indent=0;
        for (Match match=indentingRegex.Match(xml); match.Success; match=match.NextMatch()) {
              if (match.Groups["closing"].Success)
                    indent--;
              result.AppendFormat("{0}{1}\r\n", new String(' ', indent*2), match.Value);
              if (match.Groups["opening"].Success&&(!match.Groups["closing"].Success))
                    indent++;
        }
        return result.ToString();
  }
+1

Source: https://habr.com/ru/post/1703121/