MacOS下如何反向替换XML编码?解决xmllint格式化报错问题
Got it, I totally get what you're trying to do—you need to turn those escaped XML entities in your logs back into regular characters so xmllint --format stops throwing errors and gives you human-readable XML. Since you're on MacOS and have Perl available, this is straightforward.
The Core Idea
We need to reverse the standard XML entity encoding:
- Replace
&back to& - Replace
<back to< - Replace
>back to> - (Optional) Add replacements for other common entities like
"(") and'(') if your logs use them
The One-Liner Command
Pipe your log content through Perl first to un-escape the entities, then feed it to xmllint:
cat your-log-file.log | perl -pe 's/&/&/g; s/</</g; s/>/>/g;' | xmllint --format -
Breakdown of the Command:
cat your-log-file.log: Reads your log file (replace with your actual file path)perl -pe '...': Processes each line of input:s/&/&/g: Globally replaces all&with&(do this first—if you replace other entities first, you might break nested encodings)s/</</g: Replaces all escaped<with the actual less-than signs/>/>/g: Replaces all escaped>with the actual greater-than sign
xmllint --format -: Takes the cleaned input from stdin (-) and outputs formatted, human-readable XML
Optional: Handle More Entities
If your logs include quoted entities, extend the Perl script:
cat your-log-file.log | perl -pe 's/&/&/g; s/</</g; s/>/>/g; s/"/"/g; s/'/'\''/g;' | xmllint --format -
The s/'/'\''/g part uses bash's escape syntax to handle the single quote correctly.
Example
Suppose your log has this messy line:
<user><name>John&Doe</name><age>30</age></user>
After running the command, xmllint will output nicely formatted XML:
<user> <name>John&Doe</name> <age>30</age> </user>
Just make sure to replace your-log-file.log with the actual path to your log file, and you're good to go!
内容的提问来源于stack exchange,提问作者Niccolò

