Powershell XML manipulation: Keep only nodes where date is maxPowershell remove nodes from XML and remove empty lines when savingxpath: find a node that has a given attribute whose value contains a stringSearching an XML and getting a subset of the nodes as an XMLGenerate/get xpath from XML node javaXML - SelectNodes - How to get nodes with attribute with some value (MFC)Replacing XML contents and writing to diskList of nodes in a particular node in .csproj file with PowershellParsing XML with namespace with PowerShellDelete all empty nodes from XML in SQL ServerUpdate xml node value from secondary table using join based current node valueRead specific value from XML node

Does Swashbuckler's Fancy Footwork apply if the attack was made with Booming Blade?

Is a butterfly one or two animals?

Why don't we use Cavea-B

How does the government purchase things?

How to "know" if I have a passion?

Did the twin engined Lazair ultralight have a throttle for each engine?

Can you grapple/shove with the Hunter Ranger's Whirlwind Attack?

Can I submit a paper under an alias so as to avoid trouble in my country?

If all closed subsets of a set are compact, does it follow that this set is subset of a compact set?

How could China have extradited people for political reason under the extradition law it wanted to pass in Hong Kong?

Why is 日本 read as "nihon" but not "nitsuhon"?

What are the pros and cons of Einstein-Cartan Theory?

!I!n!s!e!r!t! !n!b!e!t!w!e!e!n!

Hai la patente? - omission of possessive adjective

Are required indicators necessary for radio buttons?

Are illustrations in novels frowned upon?

Should my "average" PC be able to discern the potential of encountering a gelatinous cube from subtle clues?

Why don't sharp and flat root note chords seem to be present in much guitar music?

Sous vide chicken without an internal temperature of 165 °F (75 °C)

Can a Beast Master ranger choose a swarm as an animal companion?

What is the evidence on the danger of feeding whole blueberries and grapes to infants and toddlers?

How did Apollo 15's depressurization work?

Is refusing to concede in the face of an unstoppable Nexus combo punishable?

Is there a commercial liquid with refractive index greater than n=2?



Powershell XML manipulation: Keep only nodes where date is max


Powershell remove nodes from XML and remove empty lines when savingxpath: find a node that has a given attribute whose value contains a stringSearching an XML and getting a subset of the nodes as an XMLGenerate/get xpath from XML node javaXML - SelectNodes - How to get nodes with attribute with some value (MFC)Replacing XML contents and writing to diskList of nodes in a particular node in .csproj file with PowershellParsing XML with namespace with PowerShellDelete all empty nodes from XML in SQL ServerUpdate xml node value from secondary table using join based current node valueRead specific value from XML node






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I have an XML file with the following (simplified) structure:



<XML>
<Observation>
<Dimension value="2018-11-01" />
<Value value="123" />
</Observation>
<Observation>
<Dimension value="2018-11-02" />
<Value value="456" />
</Observation>
<Observation>
<Dimension value="2018-12-01" />
<Value value="789" />
</Observation>
<Observation>
<Dimension value="2018-12-02" />
<Value value="222" />
</Observation>
</XML>


The task at hand is to delete nodes where the date in the value attribute of the Dimension node not the maximum date. Or in other words: Only the nodes containing the maximum/highest date in the value attribute of the Dimension node should be kept. This should be done per month.



Hence, the result should look as follows:



<XML>
<Observation>
<Dimension value="2018-11-02" />
<Value value="456" />
</Observation>
<Observation>
<Dimension value="2018-12-02" />
<Value value="222" />
</Observation>
</XML>


How can this be done in Powershell? I know how to read an XML file and how to make XPath-based queries:



$doc.SelectNodes("//Observation", $ns)


However, I do not know how to a) determine the maximum/highest date per month, and b) how to delete nodes that do not contain the maximum/highest date.



EDIT:



Another, maybe easier, way of doing this would be as follows:



  1. find the highest/maximium dates per month

  2. only keep nodes that
    have this date.









share|improve this question
































    0















    I have an XML file with the following (simplified) structure:



    <XML>
    <Observation>
    <Dimension value="2018-11-01" />
    <Value value="123" />
    </Observation>
    <Observation>
    <Dimension value="2018-11-02" />
    <Value value="456" />
    </Observation>
    <Observation>
    <Dimension value="2018-12-01" />
    <Value value="789" />
    </Observation>
    <Observation>
    <Dimension value="2018-12-02" />
    <Value value="222" />
    </Observation>
    </XML>


    The task at hand is to delete nodes where the date in the value attribute of the Dimension node not the maximum date. Or in other words: Only the nodes containing the maximum/highest date in the value attribute of the Dimension node should be kept. This should be done per month.



    Hence, the result should look as follows:



    <XML>
    <Observation>
    <Dimension value="2018-11-02" />
    <Value value="456" />
    </Observation>
    <Observation>
    <Dimension value="2018-12-02" />
    <Value value="222" />
    </Observation>
    </XML>


    How can this be done in Powershell? I know how to read an XML file and how to make XPath-based queries:



    $doc.SelectNodes("//Observation", $ns)


    However, I do not know how to a) determine the maximum/highest date per month, and b) how to delete nodes that do not contain the maximum/highest date.



    EDIT:



    Another, maybe easier, way of doing this would be as follows:



    1. find the highest/maximium dates per month

    2. only keep nodes that
      have this date.









    share|improve this question




























      0












      0








      0








      I have an XML file with the following (simplified) structure:



      <XML>
      <Observation>
      <Dimension value="2018-11-01" />
      <Value value="123" />
      </Observation>
      <Observation>
      <Dimension value="2018-11-02" />
      <Value value="456" />
      </Observation>
      <Observation>
      <Dimension value="2018-12-01" />
      <Value value="789" />
      </Observation>
      <Observation>
      <Dimension value="2018-12-02" />
      <Value value="222" />
      </Observation>
      </XML>


      The task at hand is to delete nodes where the date in the value attribute of the Dimension node not the maximum date. Or in other words: Only the nodes containing the maximum/highest date in the value attribute of the Dimension node should be kept. This should be done per month.



      Hence, the result should look as follows:



      <XML>
      <Observation>
      <Dimension value="2018-11-02" />
      <Value value="456" />
      </Observation>
      <Observation>
      <Dimension value="2018-12-02" />
      <Value value="222" />
      </Observation>
      </XML>


      How can this be done in Powershell? I know how to read an XML file and how to make XPath-based queries:



      $doc.SelectNodes("//Observation", $ns)


      However, I do not know how to a) determine the maximum/highest date per month, and b) how to delete nodes that do not contain the maximum/highest date.



      EDIT:



      Another, maybe easier, way of doing this would be as follows:



      1. find the highest/maximium dates per month

      2. only keep nodes that
        have this date.









      share|improve this question
















      I have an XML file with the following (simplified) structure:



      <XML>
      <Observation>
      <Dimension value="2018-11-01" />
      <Value value="123" />
      </Observation>
      <Observation>
      <Dimension value="2018-11-02" />
      <Value value="456" />
      </Observation>
      <Observation>
      <Dimension value="2018-12-01" />
      <Value value="789" />
      </Observation>
      <Observation>
      <Dimension value="2018-12-02" />
      <Value value="222" />
      </Observation>
      </XML>


      The task at hand is to delete nodes where the date in the value attribute of the Dimension node not the maximum date. Or in other words: Only the nodes containing the maximum/highest date in the value attribute of the Dimension node should be kept. This should be done per month.



      Hence, the result should look as follows:



      <XML>
      <Observation>
      <Dimension value="2018-11-02" />
      <Value value="456" />
      </Observation>
      <Observation>
      <Dimension value="2018-12-02" />
      <Value value="222" />
      </Observation>
      </XML>


      How can this be done in Powershell? I know how to read an XML file and how to make XPath-based queries:



      $doc.SelectNodes("//Observation", $ns)


      However, I do not know how to a) determine the maximum/highest date per month, and b) how to delete nodes that do not contain the maximum/highest date.



      EDIT:



      Another, maybe easier, way of doing this would be as follows:



      1. find the highest/maximium dates per month

      2. only keep nodes that
        have this date.






      xml powershell data-manipulation






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 27 at 16:31







      beta

















      asked Mar 27 at 15:29









      betabeta

      1,5656 gold badges26 silver badges57 bronze badges




      1,5656 gold badges26 silver badges57 bronze badges

























          2 Answers
          2






          active

          oldest

          votes


















          1














          Grouping by month using Group-Object simplifies the process.



          $doc.XML.Observation | Group-Object $_.Dimension.value.Substring(0,7) | foreach Sort-Object $_.Dimension.value -Descending 


          The following is the method corresponding to the case where there are multiple parent nodes.



          $doc.SelectNodes("//message:DataSet/generic:Series", $ns) | foreach Group-Object $_.ObsDimension.value.Substring(0,7) 





          share|improve this answer



























          • that's a great answer. I just need some help to finally get it to work. Since the data in my sample is simplified (no namespaces), I actually access the nodes not via the "dot notation". Hence, the last command in your solution $doc.XML.RemoveChild($_) gives me trouble.

            – beta
            Mar 28 at 9:01












          • My actual command looks like this: $doc.SelectNodes("//message:DataSet/generic:Series/generic:Obs", $ns) | Group-Object $_.ObsDimension.value.Substring(0,7) | foreach $_.Group . It gives me the following exception: Exception calling "RemoveChild" with "1" argument(s): "The node to be removed is not a child of this node.". Can you help?

            – beta
            Mar 28 at 9:02











          • Because generic: Obs is a child node of generic: Series, the node that calls RemoveChild must be generic: Series. Also, it is better to use "SelectSingleNode" if there is only one target "generic: Series" node.

            – rokumaru
            Mar 28 at 9:49











          • So, the last foreach is as follows. foreach $doc.SelectSingleNode("//message:DataSet/generic:Series", $ns).RemoveChild($_)

            – rokumaru
            Mar 28 at 9:50







          • 1





            I answered here.

            – rokumaru
            Mar 29 at 13:36


















          0














          This should do excatly what you want:



          Add-Type -AssemblyName System.Collections

          $filePath = "inputfile.xml"
          $filePath1 = "outputfile.xml"

          $xmlContent = New-Object System.Xml.XmlDocument
          $xmlContent.PreserveWhitespace = $true
          $xmlContent = [xml]([System.IO.File]::ReadLines($filePath))

          [System.Collections.Generic.List[string]]$highestValues = @()

          $oldMonth = ""
          $oldYear = ""

          $xmlContent.XML.Observation.Dimension | Sort-Object $_.value -Descending | ForEach-Object

          $currentDate = $_.value
          $currentYear = $currentDate.Substring(0,4)
          $currentMonth = $currentDate.Substring(5,2)

          if( $currentYear -ne $oldYear -or $currentMonth -ne $oldMonth )
          $oldYear = $currentYear
          $oldMonth = $currentMonth
          $highestValues.Add( $currentDate )



          $numItems = ($xmlContent.XML.Observation.Dimension).Count

          for( $i = $numItems - 1; $i -ge 0; $i-- )

          if( !$highestValues.Contains( $xmlContent.XML.Observation.Dimension[$i].value ) )
          [void]$xmlContent.XML.RemoveChild( $xmlContent.XML.Observation[$i] )




          [void]$xmlContent.Save( $filePath1 )





          share|improve this answer



























            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55380943%2fpowershell-xml-manipulation-keep-only-nodes-where-date-is-max%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            Grouping by month using Group-Object simplifies the process.



            $doc.XML.Observation | Group-Object $_.Dimension.value.Substring(0,7) | foreach Sort-Object $_.Dimension.value -Descending 


            The following is the method corresponding to the case where there are multiple parent nodes.



            $doc.SelectNodes("//message:DataSet/generic:Series", $ns) | foreach Group-Object $_.ObsDimension.value.Substring(0,7) 





            share|improve this answer



























            • that's a great answer. I just need some help to finally get it to work. Since the data in my sample is simplified (no namespaces), I actually access the nodes not via the "dot notation". Hence, the last command in your solution $doc.XML.RemoveChild($_) gives me trouble.

              – beta
              Mar 28 at 9:01












            • My actual command looks like this: $doc.SelectNodes("//message:DataSet/generic:Series/generic:Obs", $ns) | Group-Object $_.ObsDimension.value.Substring(0,7) | foreach $_.Group . It gives me the following exception: Exception calling "RemoveChild" with "1" argument(s): "The node to be removed is not a child of this node.". Can you help?

              – beta
              Mar 28 at 9:02











            • Because generic: Obs is a child node of generic: Series, the node that calls RemoveChild must be generic: Series. Also, it is better to use "SelectSingleNode" if there is only one target "generic: Series" node.

              – rokumaru
              Mar 28 at 9:49











            • So, the last foreach is as follows. foreach $doc.SelectSingleNode("//message:DataSet/generic:Series", $ns).RemoveChild($_)

              – rokumaru
              Mar 28 at 9:50







            • 1





              I answered here.

              – rokumaru
              Mar 29 at 13:36















            1














            Grouping by month using Group-Object simplifies the process.



            $doc.XML.Observation | Group-Object $_.Dimension.value.Substring(0,7) | foreach Sort-Object $_.Dimension.value -Descending 


            The following is the method corresponding to the case where there are multiple parent nodes.



            $doc.SelectNodes("//message:DataSet/generic:Series", $ns) | foreach Group-Object $_.ObsDimension.value.Substring(0,7) 





            share|improve this answer



























            • that's a great answer. I just need some help to finally get it to work. Since the data in my sample is simplified (no namespaces), I actually access the nodes not via the "dot notation". Hence, the last command in your solution $doc.XML.RemoveChild($_) gives me trouble.

              – beta
              Mar 28 at 9:01












            • My actual command looks like this: $doc.SelectNodes("//message:DataSet/generic:Series/generic:Obs", $ns) | Group-Object $_.ObsDimension.value.Substring(0,7) | foreach $_.Group . It gives me the following exception: Exception calling "RemoveChild" with "1" argument(s): "The node to be removed is not a child of this node.". Can you help?

              – beta
              Mar 28 at 9:02











            • Because generic: Obs is a child node of generic: Series, the node that calls RemoveChild must be generic: Series. Also, it is better to use "SelectSingleNode" if there is only one target "generic: Series" node.

              – rokumaru
              Mar 28 at 9:49











            • So, the last foreach is as follows. foreach $doc.SelectSingleNode("//message:DataSet/generic:Series", $ns).RemoveChild($_)

              – rokumaru
              Mar 28 at 9:50







            • 1





              I answered here.

              – rokumaru
              Mar 29 at 13:36













            1












            1








            1







            Grouping by month using Group-Object simplifies the process.



            $doc.XML.Observation | Group-Object $_.Dimension.value.Substring(0,7) | foreach Sort-Object $_.Dimension.value -Descending 


            The following is the method corresponding to the case where there are multiple parent nodes.



            $doc.SelectNodes("//message:DataSet/generic:Series", $ns) | foreach Group-Object $_.ObsDimension.value.Substring(0,7) 





            share|improve this answer















            Grouping by month using Group-Object simplifies the process.



            $doc.XML.Observation | Group-Object $_.Dimension.value.Substring(0,7) | foreach Sort-Object $_.Dimension.value -Descending 


            The following is the method corresponding to the case where there are multiple parent nodes.



            $doc.SelectNodes("//message:DataSet/generic:Series", $ns) | foreach Group-Object $_.ObsDimension.value.Substring(0,7) 






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 28 at 10:27

























            answered Mar 27 at 17:42









            rokumarurokumaru

            8581 gold badge3 silver badges9 bronze badges




            8581 gold badge3 silver badges9 bronze badges















            • that's a great answer. I just need some help to finally get it to work. Since the data in my sample is simplified (no namespaces), I actually access the nodes not via the "dot notation". Hence, the last command in your solution $doc.XML.RemoveChild($_) gives me trouble.

              – beta
              Mar 28 at 9:01












            • My actual command looks like this: $doc.SelectNodes("//message:DataSet/generic:Series/generic:Obs", $ns) | Group-Object $_.ObsDimension.value.Substring(0,7) | foreach $_.Group . It gives me the following exception: Exception calling "RemoveChild" with "1" argument(s): "The node to be removed is not a child of this node.". Can you help?

              – beta
              Mar 28 at 9:02











            • Because generic: Obs is a child node of generic: Series, the node that calls RemoveChild must be generic: Series. Also, it is better to use "SelectSingleNode" if there is only one target "generic: Series" node.

              – rokumaru
              Mar 28 at 9:49











            • So, the last foreach is as follows. foreach $doc.SelectSingleNode("//message:DataSet/generic:Series", $ns).RemoveChild($_)

              – rokumaru
              Mar 28 at 9:50







            • 1





              I answered here.

              – rokumaru
              Mar 29 at 13:36

















            • that's a great answer. I just need some help to finally get it to work. Since the data in my sample is simplified (no namespaces), I actually access the nodes not via the "dot notation". Hence, the last command in your solution $doc.XML.RemoveChild($_) gives me trouble.

              – beta
              Mar 28 at 9:01












            • My actual command looks like this: $doc.SelectNodes("//message:DataSet/generic:Series/generic:Obs", $ns) | Group-Object $_.ObsDimension.value.Substring(0,7) | foreach $_.Group . It gives me the following exception: Exception calling "RemoveChild" with "1" argument(s): "The node to be removed is not a child of this node.". Can you help?

              – beta
              Mar 28 at 9:02











            • Because generic: Obs is a child node of generic: Series, the node that calls RemoveChild must be generic: Series. Also, it is better to use "SelectSingleNode" if there is only one target "generic: Series" node.

              – rokumaru
              Mar 28 at 9:49











            • So, the last foreach is as follows. foreach $doc.SelectSingleNode("//message:DataSet/generic:Series", $ns).RemoveChild($_)

              – rokumaru
              Mar 28 at 9:50







            • 1





              I answered here.

              – rokumaru
              Mar 29 at 13:36
















            that's a great answer. I just need some help to finally get it to work. Since the data in my sample is simplified (no namespaces), I actually access the nodes not via the "dot notation". Hence, the last command in your solution $doc.XML.RemoveChild($_) gives me trouble.

            – beta
            Mar 28 at 9:01






            that's a great answer. I just need some help to finally get it to work. Since the data in my sample is simplified (no namespaces), I actually access the nodes not via the "dot notation". Hence, the last command in your solution $doc.XML.RemoveChild($_) gives me trouble.

            – beta
            Mar 28 at 9:01














            My actual command looks like this: $doc.SelectNodes("//message:DataSet/generic:Series/generic:Obs", $ns) | Group-Object $_.ObsDimension.value.Substring(0,7) | foreach $_.Group . It gives me the following exception: Exception calling "RemoveChild" with "1" argument(s): "The node to be removed is not a child of this node.". Can you help?

            – beta
            Mar 28 at 9:02





            My actual command looks like this: $doc.SelectNodes("//message:DataSet/generic:Series/generic:Obs", $ns) | Group-Object $_.ObsDimension.value.Substring(0,7) | foreach $_.Group . It gives me the following exception: Exception calling "RemoveChild" with "1" argument(s): "The node to be removed is not a child of this node.". Can you help?

            – beta
            Mar 28 at 9:02













            Because generic: Obs is a child node of generic: Series, the node that calls RemoveChild must be generic: Series. Also, it is better to use "SelectSingleNode" if there is only one target "generic: Series" node.

            – rokumaru
            Mar 28 at 9:49





            Because generic: Obs is a child node of generic: Series, the node that calls RemoveChild must be generic: Series. Also, it is better to use "SelectSingleNode" if there is only one target "generic: Series" node.

            – rokumaru
            Mar 28 at 9:49













            So, the last foreach is as follows. foreach $doc.SelectSingleNode("//message:DataSet/generic:Series", $ns).RemoveChild($_)

            – rokumaru
            Mar 28 at 9:50






            So, the last foreach is as follows. foreach $doc.SelectSingleNode("//message:DataSet/generic:Series", $ns).RemoveChild($_)

            – rokumaru
            Mar 28 at 9:50





            1




            1





            I answered here.

            – rokumaru
            Mar 29 at 13:36





            I answered here.

            – rokumaru
            Mar 29 at 13:36













            0














            This should do excatly what you want:



            Add-Type -AssemblyName System.Collections

            $filePath = "inputfile.xml"
            $filePath1 = "outputfile.xml"

            $xmlContent = New-Object System.Xml.XmlDocument
            $xmlContent.PreserveWhitespace = $true
            $xmlContent = [xml]([System.IO.File]::ReadLines($filePath))

            [System.Collections.Generic.List[string]]$highestValues = @()

            $oldMonth = ""
            $oldYear = ""

            $xmlContent.XML.Observation.Dimension | Sort-Object $_.value -Descending | ForEach-Object

            $currentDate = $_.value
            $currentYear = $currentDate.Substring(0,4)
            $currentMonth = $currentDate.Substring(5,2)

            if( $currentYear -ne $oldYear -or $currentMonth -ne $oldMonth )
            $oldYear = $currentYear
            $oldMonth = $currentMonth
            $highestValues.Add( $currentDate )



            $numItems = ($xmlContent.XML.Observation.Dimension).Count

            for( $i = $numItems - 1; $i -ge 0; $i-- )

            if( !$highestValues.Contains( $xmlContent.XML.Observation.Dimension[$i].value ) )
            [void]$xmlContent.XML.RemoveChild( $xmlContent.XML.Observation[$i] )




            [void]$xmlContent.Save( $filePath1 )





            share|improve this answer





























              0














              This should do excatly what you want:



              Add-Type -AssemblyName System.Collections

              $filePath = "inputfile.xml"
              $filePath1 = "outputfile.xml"

              $xmlContent = New-Object System.Xml.XmlDocument
              $xmlContent.PreserveWhitespace = $true
              $xmlContent = [xml]([System.IO.File]::ReadLines($filePath))

              [System.Collections.Generic.List[string]]$highestValues = @()

              $oldMonth = ""
              $oldYear = ""

              $xmlContent.XML.Observation.Dimension | Sort-Object $_.value -Descending | ForEach-Object

              $currentDate = $_.value
              $currentYear = $currentDate.Substring(0,4)
              $currentMonth = $currentDate.Substring(5,2)

              if( $currentYear -ne $oldYear -or $currentMonth -ne $oldMonth )
              $oldYear = $currentYear
              $oldMonth = $currentMonth
              $highestValues.Add( $currentDate )



              $numItems = ($xmlContent.XML.Observation.Dimension).Count

              for( $i = $numItems - 1; $i -ge 0; $i-- )

              if( !$highestValues.Contains( $xmlContent.XML.Observation.Dimension[$i].value ) )
              [void]$xmlContent.XML.RemoveChild( $xmlContent.XML.Observation[$i] )




              [void]$xmlContent.Save( $filePath1 )





              share|improve this answer



























                0












                0








                0







                This should do excatly what you want:



                Add-Type -AssemblyName System.Collections

                $filePath = "inputfile.xml"
                $filePath1 = "outputfile.xml"

                $xmlContent = New-Object System.Xml.XmlDocument
                $xmlContent.PreserveWhitespace = $true
                $xmlContent = [xml]([System.IO.File]::ReadLines($filePath))

                [System.Collections.Generic.List[string]]$highestValues = @()

                $oldMonth = ""
                $oldYear = ""

                $xmlContent.XML.Observation.Dimension | Sort-Object $_.value -Descending | ForEach-Object

                $currentDate = $_.value
                $currentYear = $currentDate.Substring(0,4)
                $currentMonth = $currentDate.Substring(5,2)

                if( $currentYear -ne $oldYear -or $currentMonth -ne $oldMonth )
                $oldYear = $currentYear
                $oldMonth = $currentMonth
                $highestValues.Add( $currentDate )



                $numItems = ($xmlContent.XML.Observation.Dimension).Count

                for( $i = $numItems - 1; $i -ge 0; $i-- )

                if( !$highestValues.Contains( $xmlContent.XML.Observation.Dimension[$i].value ) )
                [void]$xmlContent.XML.RemoveChild( $xmlContent.XML.Observation[$i] )




                [void]$xmlContent.Save( $filePath1 )





                share|improve this answer













                This should do excatly what you want:



                Add-Type -AssemblyName System.Collections

                $filePath = "inputfile.xml"
                $filePath1 = "outputfile.xml"

                $xmlContent = New-Object System.Xml.XmlDocument
                $xmlContent.PreserveWhitespace = $true
                $xmlContent = [xml]([System.IO.File]::ReadLines($filePath))

                [System.Collections.Generic.List[string]]$highestValues = @()

                $oldMonth = ""
                $oldYear = ""

                $xmlContent.XML.Observation.Dimension | Sort-Object $_.value -Descending | ForEach-Object

                $currentDate = $_.value
                $currentYear = $currentDate.Substring(0,4)
                $currentMonth = $currentDate.Substring(5,2)

                if( $currentYear -ne $oldYear -or $currentMonth -ne $oldMonth )
                $oldYear = $currentYear
                $oldMonth = $currentMonth
                $highestValues.Add( $currentDate )



                $numItems = ($xmlContent.XML.Observation.Dimension).Count

                for( $i = $numItems - 1; $i -ge 0; $i-- )

                if( !$highestValues.Contains( $xmlContent.XML.Observation.Dimension[$i].value ) )
                [void]$xmlContent.XML.RemoveChild( $xmlContent.XML.Observation[$i] )




                [void]$xmlContent.Save( $filePath1 )






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 27 at 16:36









                f6a4f6a4

                6895 silver badges12 bronze badges




                6895 silver badges12 bronze badges






























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55380943%2fpowershell-xml-manipulation-keep-only-nodes-where-date-is-max%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                    용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

                    155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해