Php 对包含xml格式的字符串进行正则表达式更改
我有一个字符串中的以下xmlPhp 对包含xml格式的字符串进行正则表达式更改,php,regex,string,Php,Regex,String,我有一个字符串中的以下xml <field1 param1="value" hun="true"> <field2 hun="true"> <field3 param2="value" hun="true"> 也许您可以对字符串执行一个简单的字符串替换,将“hun=”true“的每个实例替换为'hun=”true>,我建议使用正则表达式(或者任何字符串操作工具)来修改XML。改为通过以下小型XSLT样式表运行XML: <xsl:stylesheet v
<field1 param1="value" hun="true">
<field2 hun="true">
<field3 param2="value" hun="true">
也许您可以对字符串执行一个简单的字符串替换,将“hun=”true“的每个实例替换为
'hun=”true>,
我建议使用正则表达式(或者任何字符串操作工具)来修改XML。改为通过以下小型XSLT样式表运行XML:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- this template copies your input XML unchanged... -->
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*" />
</xsl:copy>
</xsl:template>
<!-- ...except for anything with hun="true", where it adds a new element -->
<xsl:template match="*[@hun = 'true']">
<xsl:copy-of select="." />
<newxml value="number" />
</xsl:template>
</xsl:stylesheet>
这至少会扭曲注释或CDATA节,并最终破坏属性,如果它们出于某种原因包含
hun=“true”
。XSLT是一个很好的解决方案,但我真的认为,对于这一个,我想做的更改非常简单,所以太过分了。@park:我为您的确切问题提供了一个有效的XSLT样式表(如您所述)。它如何变得更简单?;)如果您认为必须在XML上使用字符串处理,我不能阻止您这样做。顺便说一句,您的示例不是格式良好的XML(所有标记都未关闭)preg_replace('/hun=“true”>/','hun=“true”>'。“\n”“,$xmlData)代码>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- this template copies your input XML unchanged... -->
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*" />
</xsl:copy>
</xsl:template>
<!-- ...except for anything with hun="true", where it adds a new element -->
<xsl:template match="*[@hun = 'true']">
<xsl:copy-of select="." />
<newxml value="number" />
</xsl:template>
</xsl:stylesheet>
<xsl:template match="*[@hun = 'true'
and not(following-sibling::*[1][self::newxml])]
">
<xsl:copy-of select="." />
<newxml value="number" />
</xsl:template>