2015-09-04 38 views
0

如何使用powershell查找此XML中的路徑?例如,我需要找到應用程序/名的路徑= PSTest,環境/名稱= DEMO在Powershell中搜索xmls

下面是示例XML:

<Applications> 
     <Application> 
      <Name>PSTest</Name> 
      <Environment> 
       <Name>DEMO</Name> 
       <BuildPath>C:\TEST\TEST</BuildPath> 
       <Path>C:\TEST\DEMO\PSTest|C:\TEST\DEMO1\PSTest</Path> 
       <BackupPath>C:\TEST\Backup</BackupPath> 
      </Environment> 
      <Environment> 
       <Name>PROD</Name> 
       <BuildPath>C:\TEST\DEMO</BuildPath> 
       <Path>C:\TEST\PROD\PSTest|C:\TEST\PROD1\PSTest</Path> 
       <BackupPath>C:\TEST\Backup\PROD</BackupPath> 
      </Environment> 
     </Application> 
     <Application> 
      <Name>PSTestTwo</Name> 
      <Environment> 
       <Name>DEMO</Name> 
       <BuildPath>C:\TEST\TEST</BuildPath> 
       <Path>C:\TEST\DEMO\PSTestTwo|C:\TEST\DEMO1\PSTestTwo</Path> 
       <BackupPath>C:\TEST\Backup</BackupPath> 
      </Environment> 
      <Environment> 
       <Name>PROD</Name> 
       <BuildPath>C:\TEST\DEMO</BuildPath> 
       <Path>C:\TEST\PROD\PSTestTwo|C:\TEST\PROD1\PSTestTwo</Path> 
       <BackupPath>C:\TEST\Backup\PROD</BackupPath> 
      </Environment> 
     </Application> 
    </Applications> 

回答

1

您可以使用XPath字符串以查找和選擇節點:

$oXml = [Xml](Get-Content "infile.xml" | Out-String) 
$sXPath = '//Application[Name = "PSTest"]/Environment[Name = "DEMO"]' 
$sPath = ($oXml.SelectSingleNode($sXPath)).Path 
$sPath 

請記住,與PowerShell本身不同,XPath區分大小寫。

+1

不錯的答案,即將提出類似的建議。我可能做'$ oXml.SelectSingleNode('// Application [Name =「PSTest」]/Environment [Name =「DEMO」]')。Path',更易於閱讀 –

+0

這讓我想起我在處理多麼糟糕與XML。 )更新了答案,謝謝! –