XML PowerShell – Fetch all the XML Nodes with based on an Attribute Value

Welcome Forums General PowerShell Q&A XML PowerShell – Fetch all the XML Nodes with based on an Attribute Value

Viewing 3 reply threads
  • Author
    Posts
    • #203312
      Participant
      Topics: 1
      Replies: 0
      Points: -7
      Rank: Member

      I am trying to fetch all the XML nodes, where Attribute “Tag” value is “Fetch” with a XPath, without looping much using PowerShell 5.1. Please help.

      [xml] $XMLValue=@'
      <Root>
      <Child>
          <Parameter Tag="Fetch"><![CDATA["Data"]]></Parameter>
          <Parameter Tag="DontFetch"><![CDATA["Data"]]></Parameter>
      </Child>
      <Child>
         <Test>
            <Node Tag="Fetch"><![CDATA["Data"]]></Parameter>
            <Node Tag="DontFetch"><![CDATA["Data"]]></Parameter>
         </Test>
      </Child>
      <Child>
          <Test>
              <Test1>
                  <Node1 Tag="Fetch"><![CDATA["Data"]]></Parameter>
                  <Node2 Tag="DontFetch"><![CDATA["Data"]]></Parameter>
              </Test1>
          </Test>     
      </Child>
      </Root>
      '@
      • This topic was modified 1 month, 2 weeks ago by sujeetkp62.
      • This topic was modified 1 month, 2 weeks ago by sujeetkp62.
    • #203351
      Participant
      Topics: 0
      Replies: 1
      Points: 8
      Rank: Member

      I’m sorry, but your example is completely blank. Give it another whirl, or maybe upload it as a Gist for easier reading 🙂

    • #203354
      js
      Participant
      Topics: 28
      Replies: 772
      Points: 2,220
      Helping Hand
      Rank: Community Hero

      Like this? Xpath is case sensitive.

      select-xml "//*[@Tag='Fetch']" file.xml
      
      Node      Path                       Pattern
      ----      ----                       -------
      Parameter /Users/js/foo/file.xml //*[@Tag='Fetch']
      Node      /Users/js/foo/file.xml //*[@Tag='Fetch']
      Node1     /Users/js/foo/file.xml //*[@Tag='Fetch']
      

      https://www.w3schools.com/xml/xpath_syntax.asp

      • This reply was modified 1 month, 2 weeks ago by js.
      • This reply was modified 1 month, 2 weeks ago by js.
      • This reply was modified 1 month, 2 weeks ago by js.
      • This reply was modified 1 month, 2 weeks ago by js.
    • #203417
      js
      Participant
      Topics: 28
      Replies: 772
      Points: 2,220
      Helping Hand
      Rank: Community Hero

      I didn’t think xml would post here at all. You have several errors in the xml where you mix up “Node” and “Parameter”. I edited my answer to match the case.

Viewing 3 reply threads
  • You must be logged in to reply to this topic.