正则表达式可在任何xml标记中添加属性 [英] Regexp to add attribute in any xml tags

查看:147
本文介绍了正则表达式可在任何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>

所以我基本上需要regex表达式来查找任何开始标记并添加我的属性,但是我是一个完整的regex新手.

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标记中添加属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆