【问题标题】:Find and replace XML attribute values from one file to another从一个文件中查找 XML 属性值并将其替换为另一个文件
【发布时间】:2012-12-04 03:20:20
【问题描述】:

我有 2 个包含相同项目数据的 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"

感谢您提供的任何帮助

【问题讨论】:

    标签: xml xslt


    【解决方案1】:

    您可以在此处使用 document 函数,在将 XSLT 应用于 server.xml 时从第二个文档(在您的情况下为“client.xml”)查找信息

    例如,您可以定义一个变量,例如,包含 client.xml 中的所有 item 元素

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

    然后,要替换 server.xml 中的 @name 属性,您可以创建一个模板来匹配这些属性,然后从 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 文件的名称作为参数传递。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 2017-11-27
      • 2021-05-20
      • 2018-01-22
      • 2016-05-20
      • 2013-02-05
      • 1970-01-01
      相关资源
      最近更新 更多