Getting values from all nodes with specific name from XML

前端 未结 1 951
生来不讨喜
生来不讨喜 2020-12-06 13:23

I\'m having problem with the most efficient way to get all the values of the nodes with certain name from XML.

For example:



        
相关标签:
1条回答
  • 2020-12-06 13:59

    You're trying to do different things here, so you won't be able to use the exact same code for both operations.

    In your first example you want to select the value of all nodes with the name MyNode. Select the nodes with the XPath expression //MyNode and expand their #text property. There are various ways to do this, for instance with Select-Xml, as @PetSerAl suggested:

    Select-Xml -XPath '//MyNode' -Path 'C:\path\to\first.xml' |
      Select-Object -Expand Node |
      Select-Object -Expand '#text'
    

    or by importing the file as an XmlDocument object and using its SelectNodes() method:

    [xml]$xml = Get-Content 'C:\path\to\first.xml'
    $xml.SelectNodes('//MyNode') | Select-Object -Expand '#text'
    

    In your second example you want to select the value of the attribute MyArgument from all nodes that have this particular attribute. Use the XPath expression //@MyArgument to select all attributes MyArgument, then expand their value as before, like this:

    Select-Xml -XPath '//@MyArgument' -Path 'C:\path\to\second.xml' |
      Select-Object -Expand Node |
      Select-Object -Expand '#text'
    

    or like this:

    [xml]$xml = Get-Content 'C:\path\to\second.xml'
    $xml.SelectNodes('//@MyArgument') | Select-Object -Expand '#text'
    

    Side note:

    $xml = New-Object System.Xml.XmlDocument
    $xml.load('C:\path\to\your.xml')
    

    and

    [xml]$xml = Get-Content 'C:\path\to\your.xml'
    

    do the same thing, so use one or the other, not both.

    0 讨论(0)
提交回复
热议问题