从多个属性标记

时间:2017-02-24 21:32:19

标签: xml powershell

我有这种XML结构,如下所示。我需要找到属性值为" Zipcode:"的对象块。并获得OrderID前两行的值以及具有实际zipcode值的下一行。

最终结果是我需要OrderID值和邮政编码对(Smith-123,05403)。

<Object name="CustomDataList" type="TDM_List_CustomData">
  <List name="Items">
    <Object type="TDM_Item_CustomData">
      <Property name="CustomDataID" value="CD156FC1461C674F2CAFC181013FCB9822" />
      <Property name="OrderID" value="Smith-123" />
      <Property name="FieldID" value="{CCC2CBB8-BEAA-4E9B-AF2D-3E32B68821D0}" />
      <Property name="FieldCaption" value="" />
      <Property name="Value" value="35082_Site20" />
      <Property name="Kind" value="cdkInternal" />
    </Object>
    <Object type="TDM_Item_CustomData">
      <Property name="CustomDataID" value="CD58AFECE84FF24D53AFB5E2F0411EE3C9" />
      <Property name="OrderID" value="Smith-123" />
      <Property name="FieldID" value="DS_CustomizableFieldZB99" />
      <Property name="FieldCaption" value="Zipcode:" />
      <Property name="Value" value="05403" />
      <Property name="Kind" value="cdkPublic" />
    </Object>
    <Object type="TDM_Item_CustomData">
      <Property name="CustomDataID" value="CD5E584899B6274F88B05D459863006914" />
      <Property name="OrderID" value="Smith-123" />
      <Property name="FieldID" value="{62D7C382-9754-454D-A4D5-04437BFC5FE4}" />
      <Property name="FieldCaption" value="" />
      <Property name="Value" value="False" />
      <Property name="Kind" value="cdkInternal" />
    </Object>

我在下面有一些非常初学的代码,我以前在一行中只找到一个属性名称值对,但是我无法弄清楚如何在我的&#之前和之后读取行34;邮编&#34;指针。

Get-ChildItem C:\temp\pwrshell\*\*.xml | foreach {
    echo $_.FullName

    [xml]$doc = Get-Content $_
    $OrderID = $doc.SelectSingleNode("//Property[@name = 'OrderID']")

    if ($OrderID) {
        echo "OrderID: $($OrderID.value)"
    } else {
        echo "OrderID not found"
    }
}

1 个答案:

答案 0 :(得分:2)

这是获得所需值的一种可能方法。首先,找到Object元素所在的&#39; FieldCaption&#39;价值等于&#39;邮政编码:&#39; :

$query = "//Object[Property[@name = 'FieldCaption' and @value = 'Zipcode:']]"
$zipcodeObj = $doc.SelectSingleNode($query)

Object开始,您可以使用相对XPath表达式轻松获取Property元素name元素:

$orderID = $zipcodeObj.SelectSingleNode("Property[@name = 'OrderID']/@value")
$zipcode = $zipcodeObj.SelectSingleNode("Property[@name = 'Value']/@value")

输出:

λ echo $orderID.value, $zipcode.value
Smith-123
05403