簡體   English   中英

如何通過 cmd / PowerShell 讀取 xml 值

[英]How to read xml value via cmd / PowerShell

我有以下 XML 格式

如何讀取Tar Path的值

<?xml version="1.0" encoding="utf-8"?>
<Foo xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Bar Path="c:\program files\bar" />
  <Tar Path="c:\program files\tar" Include="All" />
  <Updates></Updates>
</Foo>

在這個例子中,我需要接收值: c:\\program files\\tar

按照 Alex 的評論,也可以在 PowerShell 腳本中執行此操作。

我需要將這段代碼添加到現有的 .cmd 文件中,是否可以從 .cmd 調用 PowerShell 腳本並將結果返回給 cmd?

PowerShell 解決方案:

[xml]$xml = Get-Content $args[0]
$xml.Bar.Tar.Path

VBScript 解決方案:

Set xml = CreateObject("Msxml2.DOMDocument.6.0")
xml.async = False
xml.load WScript.Arguments(0)

If xml.ParseError <> 0 Then
  WScript.Echo xml.ParseError.Reason
  WScript.Quit 1
End If

Set path = xml.SelectSingleNode("/Tar/Bar[@Path]")
WScript.Echo path.Value

在批處理文件中調用上述腳本,如下所示:

powershell -File "C:\path\to\your.ps1" "C:\path\to\your.xml"

或者像這樣:

cscript //NoLogo "C:\path\to\your.vbs" "C:\path\to\your.xml"

PowerShell 和 VBScript 都將結果寫入 STDOUT。 要將其分配回批處理變量,您需要一個像這樣的for循環(用上面的命令之一替換省略號):

for /f "tokens=*" %%p in ('...') do set pathvalue=%%p

您可以為此使用Xidel

FOR /F "delims=" %%A IN ('xidel.exe -s "C:\path\to\your.xml" -e "pathvalue:=//Tar!@Path" --output-format^=cmd') DO %%A
ECHO %pathvalue%

在同一個 .bat 文件中使用 powershell 查詢 xml

SET ARXIU=c:\catalunya.xml
FOR /F "tokens=* USEBACKQ" %%F IN (`powershell "[xml]$xml = Get-Content %ARXIU% ; $xml.Foo.Tar.Path"`) DO (
     SET RUTA=%%F
     GOTO HAVE_VALUE
)
echo Error NOT have value
GOTO :EOF

:HAVE_VALUE
echo %RUTA%

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM