如果满足日期条件,则删除XML节点

时间:2016-10-20 18:32:12

标签: xml powershell

我有一个输入XML文件,如果EndDate在01-01-1995之前,我想删除<EndDate>下的节点<AddressRow>

这是符合条件的XML文件示例。

<?xml version="1.0" encoding="UTF-8"?>
<OrganisationUnits>
    <OrganisationUnitsRow num="1">
        <OrganisationId>TEST1</OrganisationId>
        <OrganisationName>TEST PROVIDER</OrganisationName>
        <Addresses>
          <AddressesRow num="1">
            <AddressId>G72261</AddressId>
            <MainAddress>N</MainAddress>
            <NonStandardAddress>
              <LocationId>P1031587</LocationId>
              <StreetNumber>20</StreetNumber>
              <Street>UNION ROAD</Street>
              <Town>SOLIHULL</Town>
              <PostCode>B90 3DQ</PostCode>
            </NonStandardAddress>
            <StartDate>1970-12-10</StartDate>
            <EndDate>1994-12-11</EndDate>
            <AddressType/>
          </AddressesRow>
        </Addresses>
        <AcPayRef2>294288</AcPayRef2>
        <Obsolete>N</Obsolete>
    </OrganisationUnitsRow>
</OrganisationUnits>

如果弄清楚如何读取文件并删除节点ok,那就可以了。

    #Loop through the xml file and look for the node <EndDate> that exists under CMCOrganisationUnits.CMCOrganisationUnitsRow.Addresses.CMCAddressesRow
foreach ($CMCAddressesRow in $xml.CMCOrganisationUnits.CMCOrganisationUnitsRow.Addresses.CMCAddressesRow) 
    {
    #set a variable for the the node that we want to remove
    $n = $CMCAddressesRow.Item('EndDate')

    #if the node (EndDate) does exist 
    if ($n) {

        #it exists then delete the parent node also
        #$n.ParentNode.ParentNode.RemoveChild($n.ParentNode)
        }
    }
    #save the changes to the file
    $xml.Save("$path\$xml_out")

所以这会删除它是否有日期。我无法弄清楚如何测试日期值。我确实尝试使用主循环中的回调,但没有成功。

#Check the End date minimum value here
$adr_end_callback = {
  param($match)
  $current = [DateTime]$match.Groups[1].Value
  $minimum = [DateTime]'1995-01-01'

      if ($minimum -gt $current)
      {
        '<EndDate>1995-01-01</EndDate>'
      }
      else {
    '<EndDate>' + $match.Groups[1].Value + '</EndDate>'
      }
    }

也许我过度思考它并且有一个简单的答案。

1 个答案:

答案 0 :(得分:1)

$cutoffDate = Get-Date 1995-01-01
$date = Get-Date $CMCAddressesRow.EndDate

if ($date -lt $cutoffDate) {
    # delete
}