2012-12-04 50 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

相關問題