本文介绍了正则表达式在任何 xml 标签中添加属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已将格式良好的 xml 文档转换为字符串变量.我想使用 preg_replace 为每个 xml 标签添加一个定义的属性.
I have well-formed xml documents into string variables. I want to use preg_replace to add a defined attribute to every xml tags.
例如替换:
<tag1>
<tag2> some text </tag2>
</tag1>
作者:
<tag1 attr="myAttr">
<tag2 attr="myAttr"> some text </tag2>
</tag1>
所以我基本上需要正则表达式来查找任何开始标签并添加我的属性,但我是一个完整的正则表达式菜鸟.
So I basically need the regex expression to find any start tags and add my attribute, but I'm a complete regex noob.
推荐答案
不要使用正则表达式处理 xml.XML 不是常规语言.改用 php 的 xml 扩展:
Don't use regular expressions for working on xml. Xml is not a regular language. Use the xml extensions of php instead:
$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,例如:
All answers containing regular expressions will break this valid xml, for example:
<?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>
这篇关于正则表达式在任何 xml 标签中添加属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!