替换xsl文件中的XPath字符串

时间:2018-08-21 17:09:14

标签: xml xslt xpath sh

大家。 我需要以下事项的帮助。 我有一个带有XPath的XSL文件,它对应于具有UBL 2.0标准的XML文件,我需要XPath来适合UBL 2.1标准。

需要更改的文件数太多,因此,我试图使用sed命令替换每个文件中的XPath。我已经尝试了下一个命令:

sed -i 's/select="\/ns1:Invoice\/cac:AccountingSupplierParty\/cbc:CustomerAssignedAccountID"\/>/select="\/ns1:Invoice\/cac:AccountingSupplierParty\/cac:Party\/cac:PartyIdentification\/cbc:ID"\/>/g' path/to/file

XPath包含需要转义的字符,所以我的疑问是,用命令的当前结构替换路径是否没有问题

1 个答案:

答案 0 :(得分:1)

不适用于带有正则表达式的XML。

由于XSLT本身就是XML,因此可以使用XSLT对其进行编辑。从身份转换开始,并为要修改的属性添加特定的模板。

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
>    
    <xsl:template match="node() | @*">
        <xsl:copy>
            <xsl:apply-templates select="node() | @*" />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="xsl:apply-templates/@select[
      . = '/ns1:Invoice/cac:AccountingSupplierParty/cbc:CustomerAssignedAccountID'
    ]">
        <xsl:attribute name="select">
            <xsl:text>/ns1:Invoice/cac:AccountingSupplierParty/cac:Party/cac:PartyIdentification/cbc:ID</xsl:text>
        </xsl:attribute>
    </xsl:template>
</xsl:stylesheet>

适用于

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output encoding="utf-8"/>

    <xsl:template match="/">
        <xsl:apply-templates select="/ns1:Invoice/cac:AccountingSupplierParty/cbc:CustomerAssignedAccountID" />
    </xsl:template>
</xsl:stylesheet>

产生

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output encoding="utf-8"/>

    <xsl:template match="/">
        <xsl:apply-templates select="/ns1:Invoice/cac:AccountingSupplierParty/cac:Party/cac:PartyIdentification/cbc:ID"/>
    </xsl:template>
</xsl:stylesheet>
相关问题