如何获取文件中xml标记的值的长度,然后根据该xml标记的长度删除字符?

时间:2018-11-12 16:49:40

标签: xml-parsing

<LoanAddressDetails>
    <LoanAddressDetail>
        <LOAN_ADDRESS_TYPE>Mailing</LOAN_ADDRESS_TYPE>     
        <LOAN_ADDRESS_LINE_1>2197 RIDGEMONT RD</LOAN_ADDRESS_LINE_1>
        <LOAN_ADDRESS_LINE_2/>
        <LOAN_CITY>GROSSE POINTE WOO</LOAN_CITY>
        <LOAN_STATE>MI</LOAN_STATE>
        <LOAN_ZIP_CODE>48231337</LOAN_ZIP_CODE>
    </LoanAddressDetail>
</LoanAddressDetails>

1 个答案:

答案 0 :(得分:0)

要将LOAN_ZIP_CODE元素的长度限制为5个字符,您可以为此使用xsltproc(一种小型的Linux命令行XSLT-1.0处理器)。因此,请使用以下样式表test.xslt

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<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>  

  <!-- Shorten one specific text node to a maximum length of 5 -->
  <xsl:template match="LOAN_ZIP_CODE/text()">
      <xsl:value-of select="substring(.,1,5)" />
  </xsl:template>  

</xsl:stylesheet>

,并使用file.xml

将输入XML文件(此处称为target.xml)传递到输出XML文件(此处名为xsltproc)。
xsltproc -o target.xml test.xslt file.xml

输出为:

<LoanAddressDetails>
    <LoanAddressDetail>
        <LOAN_ADDRESS_TYPE>Mailing</LOAN_ADDRESS_TYPE>     
        <LOAN_ADDRESS_LINE_1>2197 RIDGEMONT RD</LOAN_ADDRESS_LINE_1>
        <LOAN_ADDRESS_LINE_2/>
        <LOAN_CITY>GROSSE POINTE WOO</LOAN_CITY>
        <LOAN_STATE>MI</LOAN_STATE>
        <LOAN_ZIP_CODE>48231</LOAN_ZIP_CODE>
    </LoanAddressDetail>
</LoanAddressDetails>

您当然可以在bash脚本中使用此命令。