【发布时间】:2021-10-01 20:57:09
【问题描述】:
所以,我的问题似乎很简单,但我被困住了。我想根据 id 属性在 xml 中填充文本元素,我的 xml 是一个如下所示的 PageXML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<PcGts xmlns="http://schema.primaresearch.org/PAGE/gts/pagecontent/2019-07-15" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://schema.primaresearch.org/PAGE/gts/pagecontent/2019-07-15 http://schema.primaresearch.org/PAGE/gts/pagecontent/2019-07-15/pagecontent.xsd">
<Metadata>
<Creator>myself</Creator>
<Created>2021-07-03T09:37:54.369908+00:00</Created>
<LastChange>2021-07-03T09:37:54.369944+00:00</LastChange>
</Metadata>
<Page imageFilename="05.tif" imageWidth="3243" imageHeight="4077">
<TextRegion id="eSc_dummyblock_">
<TextLine id="eSc_line_b74d9f71" >
<Coords points="1376,108 1390,67 1492,78 1492,166 1431,149 1407,166 1390,149 1376,156"/>
<Baseline points="1380,112 1499,112"/>
<TextEquiv>
<Unicode></Unicode>
</TextEquiv>
</TextLine>
<TextLine id="eSc_line_5aceacfb" >
<Coords points="2882,173 2882,142 2947,125 2947,292 2920,288 2882,309"/>
<Baseline points="2886,176 2954,176"/>
<TextEquiv>
<Unicode>toto</Unicode>
</TextEquiv>
</TextLine>
</TextRegion>
</Page>
</PcGts>
我只想传递一个 xslt 模板,以便根据 TextLine id 属性为每个 Unicode 元素填充不同的值。这样的事情必须有效,但是什么也没有发生。
import lxml.etree as ET
dom = ET.parse(filename)
xslt_root = etree.XML(
'''<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes" encoding="UTF-8" omit-xml-declaration="no"/>
<xsl:strip-space elements="*"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="@id[. = 'eSc_line_b74d9f71']/*/Unicode/text()[. = '']">something else</xsl:template>
</xsl:stylesheet>''')
transform = ET.XSLT(xslt_root)
newdom = transform(dom)
想要的输出:
<?xml version="1.0" encoding="UTF-8"?>
<TextRegion id="eSc_dummyblock_">
<TextLine id="eSc_line_b74d9f71">
<Coords points="1376,108 1390,67 1492,78 1492,166 1431,149 1407,166 1390,149 1376,156"/>
<Baseline points="1380,112 1499,112"/>
<TextEquiv>
<Unicode>something else</Unicode>
</TextEquiv>
</TextLine>
<TextLine id="eSc_line_5aceacfb">
<Coords points="2882,173 2882,142 2947,125 2947,292 2920,288 2882,309"/>
<Baseline points="2886,176 2954,176"/>
<TextEquiv>
<Unicode/>
</TextEquiv>
</TextLine>
</TextRegion>
感谢您的帮助
----解决方案---
正如@michael.hor257k 所建议的那样,解决方案是在 xslt 样式表中声明相同的命名空间:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:met="http://schema.primaresearch.org/PAGE/gts/pagecontent/2019-07-15"
exclude-result-prefixes="met">
<!-- identity transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="met:TextLine[@id='eSc_line_b74d9f71']/met:TextEquiv/met:Unicode">
<xsl:copy>something else</xsl:copy>
</xsl:template>
</xsl:stylesheet>
【问题讨论】:
-
请编辑您的问题并添加预期结果。还要明确“根据TextLine id属性的不同值”的意思。
标签: xslt xsd xml-parsing