2012-12-04 51 views
2

我有2个XML文件与关于相同的项目,保存在客户端和服务器上的数据。一些数据是相同的,一些属性/子元素在客户端与服务器相比是不同的。查找并从一个文件替换XML属性值到另一个

客户端数据如下所示(与多个属性不相关的比较):

<item id="1" create_dttm="05/28/2010 12:00:00 AM" name="Correct_Name"> 
     <text1>sample</text1> 
     <icon>iconurl</icon>   
</item> 

服务器数据如下所示(与多个属性和可能的​​子元素):

<item type="4" id="1" name="mispelled_name"> 
</item> 

因为这些项目的匹配是通过代码中的ID完成的,所以为server.xml进行数据输入的人员对名称并不十分小心,留下了错别字或占位符名称。这不会导致错误,但是我宁愿在安全的一面,并确保server.xml中的所有拼写错误的条目由client.xml中的正确名称替换(这些都是双重检查并且都是正确的)

是否可以运行一些脚本/代码/ xslt样式表,以将server.xml中的名称替换为client.xml中的名称?

我不是很熟悉的样式表和不知道在哪里与编码类似的东西

基本上首先,我希望它看起来像这样:

Read client.xml 
Read server.xml 

For each item in client.xml, read attributes "id" and "name" 
find item with same "id" in server.xml 
replace "name" in server.xml with value from client.xml for the item with that "id" 

感谢您的帮助,您可以提供

回答

2

您可以使用文档函数来查找来自第二个文档(在您的案例'client.xml')中的信息,当将XSLT应用于server.xml时

例如,你可以像定义一个变量,包含所有在client.xml的的项目元素

<xsl:variable name="client" select="document('client.xml')//item" /> 

然后,更换@name在server.xml中属性,你可以创建一个模板来匹配这些属性,然后输出client.xml中的值。

<xsl:template match="item/@name"> 
    <xsl:attribute name="name"> 
     <xsl:value-of select="$client[@id=current()/../@id]/@name" /> 
    </xsl:attribute> 
</xsl:template> 

以下是完整的XSLT

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

    <xsl:param name="clientXml" select="'client.xml'" /> 

    <xsl:variable name="client" select="document($clientXml)//item" /> 

    <xsl:template match="item/@name"> 
     <xsl:attribute name="name"> 
      <xsl:value-of select="$client[@id=current()/../@id]/@name" /> 
     </xsl:attribute> 
    </xsl:template> 

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

当适用于您的样品client.xml的server.xml中和文件,下面是输出

<item type="4" id="1" name="Correct_Name"></item> 

请注意,我已经在参数化'client.xml'文档的名称,因为如果需要,这将允许您在不同名称的文档上使用XSLT。您只需将第二个XML文件的名称作为参数传递即可。

+0

谢谢你,工作很棒! – user1874366

相关问题