【发布时间】:2017-08-15 16:56:43
【问题描述】:
我需要一些帮助来理解 PowerShell 中的 XML。 我有几个这样的 XML 文件:
<?xml version="1.0" encoding="UTF-8"?>
<catalog xmlns="http://www.example.com/xml/catalog/2006-10-31">
<product product-id="11210">
...
<available-flag>true</available-flag>
<online-flag>false</online-flag>
<online-flag site-id="ru">true</online-flag>
<online-flag site-id="fr">true</online-flag>
<online-flag site-id="uk">false</online-flag>
<online-flag site-id="de">true</online-flag>
...
</product>
<product product-id="50610">
...
<available-flag>true</available-flag>
<online-flag>true</online-flag>
<online-flag site-id="ru">false</online-flag>
<online-flag site-id="fr">true</online-flag>
<online-flag site-id="uk">false</online-flag>
<online-flag site-id="de">fasle</online-flag>
...
</product>
<product product-id="82929">
...
<available-flag>true</available-flag>
<online-flag>true</online-flag>
<online-flag site-id="ru">false</online-flag>
<online-flag site-id="fr">true</online-flag>
<online-flag site-id="uk">false</online-flag>
<online-flag site-id="de">true</online-flag>
...
</product>
</catalog>
我需要在 PowerShell 中获取两个元素的值:
-
<online-flag>(不带site-id属性) <online-flag site-id="ru">
对于带有product-id="50610"的产品。
我有以下代码:
$Path = "C:\Temp\0\2017-08-12_190211.xml"
$XPath = "/ns:catalog/ns:product[@product-id='50610']"
$files = Get-ChildItem $Path | Where {-not $_.PSIsContainer}
if ($files -eq $null) {
return
}
foreach ($file in $files) {
[xml]$xml = Get-Content $file
$namespace = $xml.DocumentElement.NamespaceURI
$ns = New-Object System.Xml.XmlNamespaceManager($xml.NameTable)
$ns.AddNamespace("ns", $namespace)
$product = $xml.SelectSingleNode($XPath, $ns)
}
几个问题:
-
使用此代码,我可以选择所需的产品节点。 PowerShell 显示:
online-flag : {true, online-flag, online-flag, online-flag...}但是我如何才能选择所需
online-flag元素的值(如果两种方式都可以:XPath 一种和对象一种)? -
是否可以以“对象”方式选择节点?像这样:
$product = $xml.catalog.product | Where-Object {$_."product-id".value -eq "50610"} 如果我有多个文件,选择文件名、全局在线标志(无属性)、特定在线标志的最佳方法是什么?
【问题讨论】:
标签: xml powershell xpath