2009-11-26 32 views
0

你的好日子,HOWTO解析子元素到另一個相關因素

我使用Castor映射的網絡基礎架構到Java類。我的XML文件是這樣的:

<SPECTRUM_Topology> 
    <Topology> 
    <!-- Device information --> 
    <Device ip_dnsname="172.20.162.1" ... /> 
    </Topology> 
    <Update> 
    <Device ip_dnsname="172.20.162.1"> 
     <!-- Port information --> 
     <Port ... /> 
     <Port ... /> 
    </Device> 
    </Update> 
</SPECTRUM_Topology> 

我需要的文件,看起來像這樣:

<SPECTRUM_Topology> 
    <Topology> 
    <!-- Device information --> 
    <Device ip_dnsname="172.20.162.1" ...> 
     <!-- Port information --> 
     <Port ... /> 
     <Port ... /> 
    </Device> 
    </Topology> 
</SPECTRUM_Topology> 

有沒有辦法通過XSLT做到這一點?

回答

2

當然。只需創建一個與拓撲中的設備標籤相匹配的特定模板,並在其中插入更新/設備標籤內容。

這可能讓你開始:

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

    <xsl:key name="devices" match="/SPECTRUM_Topology/Update/Device" use="@ip_dnsname"/> 

    <xsl:template match="Device"> 
     <xsl:copy> 
      <xsl:apply-templates select="@*"/> 
      <xsl:apply-templates select="key('devices', @ip_dnsname)/*"/> 
     </xsl:copy> 
    </xsl:template> 

    <xsl:template match="@* | node()"> 
     <xsl:if test="not(self::Update)"> 
      <xsl:copy> 
       <xsl:apply-templates select="@* | node()"/> 
      </xsl:copy> 
     </xsl:if> 
    </xsl:template> 
</xsl:stylesheet> 
+0

謝謝,我會採取它看看。 – punischdude 2009-11-26 10:50:21

+0

工作完美!謝謝 :) – punischdude 2009-11-30 10:08:34