如果您的HTML是XHTML(格式良好)(或者如果您可以使用JTidy將其轉換爲XHTML),則可以使用XSLT轉換將名稱屬性的內容複製到新的id屬性中。
這個樣式表:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:output method="html" indent="yes"/>
<xsl:template match="@*">
<xsl:attribute name="{name()}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>
<xsl:template match="*">
<xsl:copy>
<xsl:apply-templates select="*|@*|text()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="input">
<xsl:copy>
<xsl:attribute name="id">
<xsl:value-of select="@name" />
</xsl:attribute>
<xsl:apply-templates select="@*" />
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
將文件轉換與此內容:
<form>
<div class="inputs">
<p style="color:red">Text</p>
<input type="text" name="a" />
<input type="password" name="b" />
<input type="checkbox" name="c" />
<input type="radio" name="d" />
</div>
</form>
進入這個(增加了一個新的id
屬性,每個input
與name
屬性的內容):
<form>
<div class="inputs">
<p style="color:red">Text</p>
<input id="a" type="text" name="a">
<input id="b" type="password" name="b">
<input id="c" type="checkbox" name="c">
<input id="d" type="radio" name="d">
</div>
</form>
您可以運行XSLT處理器使用命令行工具行Saxon。
我會建議一個正則表達式搜索並替換爲此;但是如果沒有對「輸入」元素屬性的(一致性)的意義 - 例如他們是否已經擁有'id'屬性,他們的'name'和'id'屬性'順序是否一致,等等。你能否提供一個你想要轉換的(清理過的)例子? – J0e3gan
'name =「my-field」'to'name =「my-field」id =「my-field」@ @ J0e3gan不幸的是我不熟練地使用regexes。 – Ivan