2012-10-09 68 views
1

我的powershell代碼實際上是從XML讀取數據並將特定數據存儲到csv文件。 的XML文件有些看起來像下面:如何使用Powershell腳本從主字符串中刪除子字符串?

<?xml version="1.0" encoding="utf-8"?> 
<Report Version="10.0"> 
<Targets> 
<Target Name="\\bin\testBusiness.dll"> 
<Modules> 
<Module Name="testing.dll" AssemblyVersion="1.0.1003.312" FileVersion="1.0.0.0"> 
<Metrics> 
<Metric Name="Maintainability" Value="78" /> 
</Metrics> 
</Module> 
</Modules> 
</Target> 
</Targets> 
</Report> 

我需要只提取 「testing.dll」從上面的XML代碼。我使用這樣做的代碼如下:

$testDLL = [regex]::matches($xmlfile[5], '<mod name=".*" ')[0].value -replace '<mod name="(.*)" ','$1' 
#the above code line gets even the AssemblyVersion 
$testAssembver = [regex]::matches($xmlfile[5], 'AssemblyVersion=".*" ')[0].value -replace 'AssemblyVersion=".*" ','$1' 

我不需要的AssemblyVersion要連接到從XML代碼「testing.dll(MOD名XML)」。

目前我得到的是這樣的:

testing.dll" AssemblyVersion=1.0.1000.112" 

我只需要testing.dll,此後一切都應該ommitted。

請幫忙。

感謝, 阿希什

回答

3

我不認爲正則表達式解析XML的最佳方式。也許你最好使用XMLDocument。

使用更好的XML文檔:

<Dumy> 
<Report Version="10.0"></Report> 
<Goals> 
    <Name>"\\somepath\path.dll"</Name> 
    <Mods> 
    <Mod Name="testing.dll" AssemblyVersion="1.0.1000.112" FileVersion="1.0.0.1"></Mod> 
    </Mods> 
</Goals> 
</Dumy> 

你可以找到你的數據是這樣的:

$data = [XML](Get-Content "C:\temp\test.xml") 
$data.Dumy.Goals.Mods.Mod.Name 
+0

感謝您的effor JPBlanc。但有沒有出路 - 使用兩次或更換其他東西。我得到的testing.dll,但隨着我需要省略的AsemblyVersion。 –

+0

當我使用您的代碼時,我實際上將該字段視爲空白。 ( –

+0

)你能提取你的確切XML代碼的一部分嗎(合適的)? – JPBlanc

0

使用XML作爲正確地JPBlanc建議。然後使用XPath。例如,提取想要的值:

$data.selectnodes("//Modules/Module/@Name") 
+0

非常感謝JPBlanc和Empo!工作。:) –

相關問題