Extract XML Element

Welcome Forums General PowerShell Q&A Extract XML Element

Viewing 3 reply threads
  • Author
    Posts
    • #215784
      Participant
      Topics: 1
      Replies: 1
      Points: 14
      Rank: Member

      Hi, I’m new to working with Powershell and would appreciate some help with extracting the element from an XML file and then output this to a txt file using powershell.

      <?xml version="1.0" encoding="utf-8"?>
      <Generic version="1.0.0">
      <ValueId>12345678</ValueId>
      <ServerIP>127.0.0.1</ServerIP>
      </Generic>
      
      
       I've been able to extract the value 12345678 to a file using this powershell;
      
      
      $XML = [XML](Get-Content C:\source.xml)
      $XML.Generic.ValueId | Out-File C:\output.txt
      
      
       I'm struggling to get this exact <ValueId>12345678</ValueId> output to the output.txt 
      
      Thanks
    • #215817
      Participant
      Topics: 12
      Replies: 1607
      Points: 2,495
      Helping Hand
      Rank: Community Hero

      Use SelectSingleNode and if you want the XML specify OuterXML:

      [xml]$xml = @"
      <?xml version="1.0" encoding="utf-8"?>
      <Generic version="1.0.0">
      <ValueId>12345678</ValueId>
      <ServerIP>127.0.0.1</ServerIP>
      </Generic>
      "@
      
      $xml.SelectSingleNode('//Generic/ValueId').OuterXml
      
    • #215850
      Participant
      Topics: 1
      Replies: 1
      Points: 14
      Rank: Member

      Thanks for the quick reply, that works perfectly.

    • #215898
      js
      Participant
      Topics: 29
      Replies: 807
      Points: 2,420
      Helping Hand
      Rank: Community Hero

      Nice job displaying the xml. Another way with select-xml:

      (select-xml //ValueId source.xml).node.OuterXml
           
      <ValueId>12345678</ValueId>
      • This reply was modified 1 month, 2 weeks ago by js.
      • This reply was modified 1 month, 2 weeks ago by js.
Viewing 3 reply threads
  • You must be logged in to reply to this topic.