Python 如果子值等于另一个值,则更改XML孙子值
我需要更正几百个XML文件 假设文件的格式如下:Python 如果子值等于另一个值,则更改XML孙子值,python,xml,parsing,element,elementtree,Python,Xml,Parsing,Element,Elementtree,我需要更正几百个XML文件 假设文件的格式如下: <?xml version="1.0" encoding="UTF-8"?> <MyData xmlns="urn:iso" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:iso"> <Hdr> <AppHdr xmlns="urn:iso" xmlns:xsi="http://www
<?xml version="1.0" encoding="UTF-8"?>
<MyData xmlns="urn:iso" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:iso">
<Hdr>
<AppHdr xmlns="urn:iso" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:iso">
<St>A</St>
<To>Z</To>
</Hdr>
<Data>
<Document xmlns="urn:iso" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:iso">
<CountryReport>
<RptHdr>
<RpDtls>
<Dt>2018-07-10</Dt>
</RpDtls>
</RptHdr>
<Country>
<Id>PT</Id>
<FullNm>Portugal</FullNm>>
<Bd>
<Tp>US</Tp>
</Bd>
</Country>
<Country>
<Id>ESP</Id>
<FullNm>Spain</FullNm>>
<Bd>
<Tp>EUR</Tp>
</Bd>
</Country>
</CountryReport>
</Document>
</Data>
</MyData>
A.
Z
2018-07-10
PT
葡萄牙>
美国
ESP
西班牙>
欧元
我需要做的替换如下:
- 如果国家ID为PT,我需要将Bd/Tp替换为“EUR”
您能帮忙吗?实现目标的最简单方法是使用XSLT处理器。例如,使用调用Linux程序或Windows/Linux程序的脚本 因为元素位于名称空间中,所以必须为元素定义名称空间。例如,将
xmlns:ui=“urn:iso”
添加到xsl:stylesheet
元素中,然后将以下模板与标识模板结合使用:
实现目标的最简单方法是使用XSLT处理器。例如,使用调用Linux程序或Windows/Linux程序的脚本 因为元素位于名称空间中,所以必须为元素定义名称空间。例如,将
xmlns:ui=“urn:iso”
添加到xsl:stylesheet
元素中,然后将以下模板与标识模板结合使用:
您好,欢迎光临。也许可以尝试发布您尝试过的内容以及您怀疑有“错误xpath”的地方。当人们看到迄今为止所做的努力,并且能够帮助解决您遇到的特定问题时,他们通常会更乐于提供帮助。您好,欢迎光临。也许可以尝试发布您尝试过的内容以及您怀疑有“错误xpath”的地方。当人们看到到目前为止所做的努力并能够帮助解决您遇到的特定问题时,他们通常会更乐于提供帮助。或者您可以使用Python运行XSLT 1.0。或者您可以使用Python运行XSLT 1.0。
<xsl:template match="ui:Country[ui:Id='PT']/ui:Bd/ui:Tp">
<xsl:element name="Tp" namespace="{namespace-uri()}">EUR</xsl:element>
</xsl:template>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*" />
</xsl:copy>
</xsl:template>
<xsl:mode on-no-match="shallow-copy" />
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ui="urn:iso">
<xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/>
<!-- identity template -->
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*" />
</xsl:copy>
</xsl:template>
<xsl:template match="ui:Country[ui:Id='PT']/ui:Bd/ui:Tp">
<xsl:element name="Tp" namespace="{namespace-uri()}">EUR</xsl:element>
</xsl:template>
</xsl:stylesheet>
for file in *; do xsltproc transform.xslt $file > $file.NEW; done;