Regex to Indent an XML File

前端 未结 7 1921
攒了一身酷
攒了一身酷 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:35

    Using a regex for this will be a nightmare. Keeping track of the indentation level based on the hierarchy of the nodes will be almost impossible. Perhaps perl's 5.10 regular expression engine might help since it's now reentrant. But let's not go into that road... Besides you will need to take into account CDATA sections which can embed XML declarations that need to be ignored by the indentation and preserved intact.

    Stick with DOM. As it was suggested in the other answer, some libraries provide already a function that will indent a DOM tree for you. If not building one will be much simplier than creating and maintaining the regexes that will do the same task.

提交回复
热议问题