不要在XML上使用正则表达式。Xml不是常规语言。请改用php的xml扩展名:
$xml = new SimpleXml(file_get_contents($xmlFile));
function process_recursive($xmlNode) {
$xmlNode->addAttribute('attr', 'myAttr');
foreach ($xmlNode->children() as $childNode) {
process_recursive($childNode);
}
}
process_recursive($xml);
echo $xml->asXML();
所有包含正则表达式的答案都将破坏此有效xml,例如:
<?xml version="1.0" encoding='UTF-8'?>
<html>
<head>
<!-- <Meta> ... </Meta> -->
<script>//<![CDATA[
function load() {document.write('<tt>Test</tt>');}
//]]></script>
<title><![CDATA[Fancy <<SiteName>> [with Breadcrumbs] > in > title]]></title>
</head>
<body onload="load()">
<input
type="submit"
value="multiline
button
text"
/>
</body>
</html>