【问题标题】:Compare the attributes in the two similar XPaths比较两个相似 XPath 中的属性
【发布时间】:2022-01-25 14:11:29
【问题描述】:

XML:

    <Emp id= "1">
    <EmpAdd num = "1">
        <Add city  = "Brentwood" c2 = "TN" c3 = "US" c4 = "37027" c5="" c6=""/>
    </EmpAdd>
    <List>
        <Emp id= "1">
            <EmpAdd num = "1">
                <Add city  = "Oswego" c2 = "TN" c3 = "US"  c7=""/>
            </EmpAdd>
        </Emp>
    </List>
</Emp>

我想比较两个 XPath 中具有相同元素名称的属性 “Emp/EmpAdd/Add”和“List/Emp/EmpAdd/Add”。两个 XPath 中的属性编号不同。

同样基于此,在 Emp/List/Emp/@IsModified 中添加一个新属性 IsModified,如果任何比较(城市、c2、c3)属性值不同,则将值设置为“Y”,否则为“N”。 我已经尝试过了,但它没有按预期工作。

我想要的改造后:

<Emp id="1">
   <EmpAdd num="1">
      <Add city="Brentwood" c2="TN" c3="US" c4="37027" c5="" c6=""/>
   </EmpAdd>
   <List>
      <Emp id="1" IsModified="Y"/>
   </List>
</Emp>

但我在输出中得到“N”。

XSLT 代码尝试:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="node()|@*">
     <xsl:copy>
       <xsl:apply-templates select="node()|@*"/>
     </xsl:copy>
 </xsl:template>
 

 <xsl:template match = "List/Emp/EmpAdd">

 <xsl:choose>
     <xsl:when test="((Emp/EmpAdd/Add/@City != List/Emp/EmpAdd/Add/@City)
    or  (Emp/EmpAdd/Add/@C2!= List/Emp/EmpAdd/Add/@C2)
    or (Emp/EmpAdd/Add/@C3 != List/Emp/EmpAdd/Add/@C3)) ">
    <xsl:attribute name="IsModified">Y</xsl:attribute> 
    </xsl:when>
    <xsl:otherwise>
         <xsl:attribute name="IsModified">N</xsl:attribute> 
    </xsl:otherwise>
</xsl:choose>
  
</xsl:template>

</xsl:stylesheet>

我并不精通 XSLT。谁能帮我解决这个问题?

【问题讨论】:

    标签: xml xslt xpath comparison


    【解决方案1】:

    如果属性的名称是 city,那么您的 XPath 需要是 @city 而不是 @City。其他属性名称也一样。

    当然,在某个节点的上下文中,例如匹配元素EmpAdd,您需要相对于该元素的路径:

    <xsl:template match = "List/Emp/EmpAdd">
     <xsl:choose>
         <xsl:when test="((../../../EmpAdd/Add/@city != Add/@city)
        or  (../../../EmpAdd/Add/@c2!= Add/@c2)
        or (../../../EmpAdd/Add/@c3 != Add/@c3)) ">
        <xsl:attribute name="IsModified">Y</xsl:attribute> 
        </xsl:when>
        <xsl:otherwise>
             <xsl:attribute name="IsModified">N</xsl:attribute> 
        </xsl:otherwise>
    </xsl:choose>
    </xsl:template>
    

    【讨论】:

      猜你喜欢
      • 2015-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-02
      • 1970-01-01
      相关资源
      最近更新 更多