且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从 XML 中获取具有特定名称的所有节点的值

更新时间:2023-01-17 18:23:26

您在这里尝试做不同的事情,因此您将无法对这两种操作使用完全相同的代码.

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

在您的第一个示例中,您要选择名称为 MyNode 的所有节点的值.选择具有 XPath 表达式 //MyNode 的节点并展开他们的 #text 属性.有多种方法可以做到这一点,例如使用 Select-Xml代码>,正如@PetSerAl 建议的那样:

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'

或通过将文件导入为 XmlDocument 对象并使用其 SelectNodes() 方法:

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'

在您的第二个示例中,您希望从具有此特定属性的所有节点中选择属性 MyArgument 的值.使用 XPath 表达式 //@MyArgument 选择所有属性 MyArgument,然后像以前一样扩展它们的值,如下所示:

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'

或者像这样:

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

附注:

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

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

做同样的事情,所以选择一个,而不是两个.

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