我有这个xml,我需要获取CPU信息,但数字部分的标签CPU"1"
可能会改变。我怎样才能给出一个xpath,以便动态地将数字部分照到n
?
我的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.@BRAND,"NA",it.@SPEED,"NA"))
}
return cpuinfo
}
else{
cpuinfo.add(new cpu("NA","NA","NA","NA"))
return cpuinfo
}
}
catch(Exception e){
println "getCpuInfo "+e
}
}
}
答案 0 :(得分:0)
我认为您应该以这种方式重写WindowsHelper类的getCpuInfo()方法:
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(node.@BRAND, "NA", node.@SPEED, "NA"))
}
}
}
if (!cpuinfo) {
cpuinfo.add(new cpu("NA","NA","NA","NA"))
}
return cpuinfo
} catch(Exception e) {
println "getCpuInfo "+e
}
}