2012-08-28 52 views
0

我有這個xml我需要獲取CPU的信息,但數字部分的標籤CPU"1"可能會改變。我怎麼能給一個xpath,以便它動態地像數字部分一樣,直到n如何給動態xpaths使用Groovy XmlParser從xml獲取數據?

我的XML內容

<CLIENT> 
<SYSTEM> 
<CPU1 NUMBER="2" SPEED="2300 MHz" Vendor="Advanced Micro Devices" BRAND="AMD Opteron(tm) Processor 6134"></CPU1> 
<CPU2 NUMBER="3" SPEED="2300 MHz" Vendor="Advanced Micro Devices" BRAND="AMD Opteron(tm) Processor 6134"></CPU2> 
</SYSTEM> 
</CLIENT> 

目前我得到的東西像下面從給出的代碼生成的XML

<client> 
<system> 
<cpuinfo> 
    <cpu Name="AMD Opteron(tm) Processor 6134" L2CacheSize="NA" MaxClockSpeed="2300 MHz" LoadPercentage="NA"/> 
</cpuinfo> 
</system> 
</client> 

我的代碼

@XStreamAlias("cpu") 
class cpu{ 
    @XStreamAsAttribute 
    String Name 
    @XStreamAsAttribute 
    String L2CacheSize 
    @XStreamAsAttribute 
    String MaxClockSpeed 
    @XStreamAsAttribute 
    String LoadPercentage 

    public cpu(String name, String l2CacheSize, String maxClockSpeed,String loadPercentage) { 
     super(); 
     Name = name; 
     L2CacheSize = l2CacheSize; 
     MaxClockSpeed = maxClockSpeed; 
     LoadPercentage = loadPercentage; 
    } 

} 


@XStreamAlias("system") 
public class WindowsSystem extends CSMSystem{ 
    List<cpu> cpuinfo 

    public WindowsSystem(CSMConfig config, String fileContent){ 
     super(config) 

     cpuinfo = new ArrayList<cpu>() 
     WindowsHelper wh=new WindowsHelper(fileContent) 
     cpuinfo=wh.getCpuInfo(cpuinfo) 
    } 
} 


class WindowsHelper { 
    private def root 
    private List<cpu> cpuinfo 

    WindowsHelper(String fileContents) 
    { 
     root=new XmlParser(false,false).parseText(fileContents) 
    } 
    def getCpuInfo(List<cpu> cpuinfo) 
    { 
     try{ 
      def cpusize="${root.SYSTEM.CPU1.size()}" 
      if(cpusize>0){ 
       root.SYSTEM.CPU1.each{ 
        cpuinfo.add(new cpu(it.[email protected],"NA",[email protected],"NA")) 
       } 
       return cpuinfo 
      } 
      else{ 
       cpuinfo.add(new cpu("NA","NA","NA","NA")) 
       return cpuinfo 
      } 
     } 
     catch(Exception e){ 
      println "getCpuInfo "+e 
     } 
    } 
} 

回答

0

我想你應該重寫getCpuInfo() WindowsHelper類的方法如下:

def getCpuInfo(List<cpu> cpuinfo) 
{ 
    try { 
     def cpusize=root.SYSTEM[0].children().size()    
     if (cpusize > 0) { 
      root.SYSTEM[0].children().each { node -> 
       if (node.name() ==~ /(?i)cpu\d+/) { 
        cpuinfo.add(new cpu([email protected], "NA", [email protected], "NA")) 
       } 
      } 
     } 

     if (!cpuinfo) { 
      cpuinfo.add(new cpu("NA","NA","NA","NA"))     
     } 

     return cpuinfo 

    } catch(Exception e) { 
     println "getCpuInfo "+e 
    } 
} 
+0

'SYSTEM'標籤也會有其他子標籤,我認爲在這種情況下'cpusize = root.SYSTEM.size()'會失敗 – abi1964

+0

我稍微修改了代碼以適應新的條件。 –