Regex to Indent an XML File

前端 未结 7 1895
攒了一身酷
攒了一身酷 2020-12-21 06:14

Is it possible to write a REGEX (search replace) that when run on an XML string will output that XML string indented nicely?

If so whats the REGEX :)

7条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-21 06:34

    From this link:

      private static Regex indentingRegex=new Regex(@"\<\s*(?[\w\-]+)(\s+[\w\-]+\s*=\s*""[^""]*""|'[^']*')*\s*\>[^\<]*\<\s*/\s*\k\s*\>|\<[!\?]((?<=!)--((?!--\>).)*--\>|(""[^""]*""|'[^']'|[^>])*\>)|\<\s*(?/)?\s*[\w\-]+(\s+[\w\-]+\s*=\s*""[^""]*""|'[^']*')*\s*((/\s*)|(?))\>|[^\<]*", 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();
      }
    

提交回复
热议问题