代码之家  ›  专栏  ›  技术社区  ›  Payal M

使用xpath和xsl遍历xml文档

  •  0
  • Payal M  · 技术社区  · 8 年前

    我使用XSL和XPATH遍历、读取和转换一个复杂的XML文件,其中有多个名称相同但值不同的节点。下面是我的示例xml文件-

        <core>
       <address>
          <postalZipCode>90017</postalZipCode>
          <updateSource>xxxxxx</updateSource>
          <city>LOS ANGELES</city>
          <stateProvince>CA</stateProvince>
          <type>MAILING</type>
          <line1>818 WEST SEVENTH STREET</line1>
       </address>
       <address>
          <postalZipCode>95014</postalZipCode>
          <updateSource>xxxxxx</updateSource>
          <city>CUPERTINO</city>
          <stateProvince>CA</stateProvince>
          <type>PRIMARY</type>
          <line1>1234 XYZ STREET</line1>
       </address>
        <memberId>0</memberId>
     </core>
    

        <xsl:template match="core">       
        <xsl:if test="memberId['0'] and address/type['MAILING']">
        <fo:table-row>
            <fo:table-cell><fo:block /></fo:table-cell>                     
            <fo:table-cell xsl:use-attribute-sets="data">
                <fo:block>Line 1</fo:block>
            </fo:table-cell>
            <fo:table-cell xsl:use-attribute-sets="data">
                <fo:block><xsl:value-of select="address/line1/text()"/>
            </fo:block>
            </fo:table-cell>                                              
        </fo:table-row>
    

    这里的专家能否建议,是否有其他方法可以强制XSL读取地址所在位置的正确值,而不是读取它找到的第一个值???

    2 回复  |  直到 8 年前
        1
  •  1
  •   michael.hor257k    8 年前

    如果有任何其他方法可以强制XSL读取正确的 地址邮寄位置的值,而不是读取第一个值

    示例中的第一个地址,以及您显示的代码片段

    在任何情况下,为了确保您从邮寄地址获得数据,无论其位置如何,请更改以下内容:

    <xsl:value-of select="address/line1/text()"/>
    

    收件人:

    <xsl:value-of select="address[type='MAILING']/line1"/>
    

    要了解其工作原理,请阅读更多关于 predicates .

        2
  •  1
  •   Michael Kay    8 年前

    xsl:value-of

    如果有多个节点,并且您想要选择一个特定的节点,那么使用谓词选择它,例如。 xsl:value-of select="address[@type='MAILING']/line1 .