匹配和更新 2 个 xml 中的属性 [英] Matching and updating attributes in 2 xmls

查看:21
本文介绍了匹配和更新 2 个 xml 中的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过匹配两个 xml 中的属性来使用另一个 xml 中的属性更新 xml 中的属性值.

I am trying to update attribute's value in xml with attribute from another xml by matching attributes in both xmls.

xml1:

<?xml version="1.0" encoding="utf-8"?>
<Products>
    <Product>
        <List prodId="123456" sellId="">        
        </List>
    </Product>
</Products>

xml2:

<?xml version="1.0" encoding="utf-8"?>
<Products>
    <Product>
        <info prodId="123456" sellId="121">         
            <qnty>4</qnty>
        </info>
        <info prodId="23456" sellId="890">          
            <qnty>1</qnty>
        </info>
    </Product>
</Products>

我需要通过 prodId 属性在第二个 xml 中进行节点,并且从该节点我需要获取属性 sellId="890" 并填充到第一个 xml 中.

I need to node, in second xml by prodId attribute, and from that node I need to take the attribute sellId="890" and populate in first xml.

所需的输出:

<?xml version="1.0" encoding="utf-8"?>
<Products>
    <Product>
        <List prodId="123456" sellId="890">        
        </List>
    </Product>
</Products>

这是我的 xsl

<xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
  version="1.0">  
  <xsl:output method="xml" indent="yes"/>

  <xsl:param name="f1" select="'xml2.xml'"/>    
  <xsl:variable name="doc1" select="document($f1)"/>  

  <xsl:key name="k1" match="Products/Product/info" use="@prodId"/>

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

    <xsl:template match="Products/Product/List">

      <xsl:variable name="tprodId" select="@prodId"/>
      <xsl:for-each select="$doc1">
        <xsl:attribute name="sellId">
                 <xsl:value-of select="key('k1', $tprodId)/@sellId"/>
              </xsl:attribute>                  
      </xsl:for-each>      

  </xsl:template>

推荐答案

我建议你这样做:

<xsl:template match="List" >
    <xsl:copy>
        <xsl:apply-templates select="@*"/>
        <xsl:variable name="tprodId" select="@prodId"/>
        <xsl:for-each select="$doc1">
            <xsl:copy-of select="key('k1', $tprodId)/@sellId"/>                
        </xsl:for-each>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>

或者,如果您愿意:

<xsl:template match="@sellId" >
    <xsl:variable name="tprodId" select="../@prodId"/>
    <xsl:for-each select="$doc1">
        <xsl:copy-of select="key('k1', $tprodId)/@sellId"/>                
    </xsl:for-each>         
</xsl:template>

这篇关于匹配和更新 2 个 xml 中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆