1

我的 powershell 代码实际上是从 XML 读取数据并将特定数据存储到 csv 文件中。XML 文件有点如下所示:

<?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>

我只需要从上述 XML 代码中提取“testing.dll” 。我用来这样做的代码如下:

$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(xml 中的模块名称)”。

目前我得到类似的东西:

 testing.dll" AssemblyVersion=1.0.1000.112" 

我只需要 testing.dll,之后的所有内容都应该省略。

请帮忙。

谢谢,阿希什

4

2 回答 2

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
于 2012-10-09T11:47:31.007 回答
0

按照 JPBlanc 的正确建议使用 XML。然后使用 XPath。例如,提取想要的值:

$data.selectnodes("//Modules/Module/@Name")
于 2012-10-10T09:55:25.800 回答