【问题标题】:Powershell: xml reading using XML-object not retrieving values if there is only one elementPowershell:如果只有一个元素,则使用 XML 对象读取 xml 不检索值
【发布时间】:2017-03-12 17:39:58
【问题描述】:
param
(
   $xmlFile="D:\Servers.xml"
)
Import-Module WebAdministration
[xml]$xmlDoc = Get-Content -Path $xmlFile
for ($i=0; $i -lt $xmlDoc.root.Servers.Server.Length; $i++)
{
     write-host "Server $i =    " $xmlDoc.root.Servers.Server[$i].Name
}

#--------------------- XML ---------------#
<xml>
<root>
   <Servers>
     <Server><ip>10.2.2.1</ip><website>abc</website>
     </Server>
       ....
     <Server><ip>10.2.2.2</ip><website>pqr</website>
     </Server>
   </Servers>
</root>
</xml>

Powershell: 问题: 问题是如果只有一个服务器节点,“$xmlDoc.root.Servers.Server[$i]”不起作用,因为对象被认为是单一的。除了写额外的 if 之外,我们有什么办法可以解决这个问题。基本上我想遍历 xml 文件并为每个服务器做一些操作。

谢谢, 哈努曼特

【问题讨论】:

    标签: xml powershell


    【解决方案1】:

    您似乎在服务器对象上没有名为“名称”的属性。 我相信您可以执行以下操作来达到您想要的结果:

    param
    (
       $xmlFile="D:\Servers.xml"
    )
    Import-Module WebAdministration
    [xml]$xmlDoc = Get-Content -Path $xmlFile
    $i = 1
    foreach($server in $xmldoc.xml.root.Servers.server){
        write-host ("Server {0} =    {1}" -f $i, $server.ip)
        $i++
    }
    

    或者,如果您不想使用字符串格式(但根据我的经验不太可读):

    param
    (
       $xmlFile="D:\Servers.xml"
    )
    Import-Module WebAdministration
    [xml]$xmlDoc = Get-Content -Path $xmlFile
    $i = 1
    foreach($server in $xmldoc.xml.root.Servers.server){
        write-host "Server $i =    $($server.ip)"
        $i++
    }
    

    当然如果你想显示XML节点的网站,那么你可以将$server.ip替换为$server.website。

    【讨论】:

    • 基本上使用 foreach 而不是 for 循环中的索引数组。这样,它既可以满足单个结果,也可以满足多个结果。
    【解决方案2】:

    使用SelectNodes 的XPath 查询工作正常,因为它将返回XmlNodeList。它是一个集合,所以即使没有结果也只会产生一个长度为零的集合。像这样,

    # Create the XML doc via here-string
    [xml]$d= @'
    <xml>
      <root>
        <Servers>
          <Server>
            <ip>10.2.2.1</ip>
            <website>abc</website>
          </Server>
        </Servers>
      </root>
    </xml>
    '@
    
    # XPath query    
    $n=$doc.SelectNodes("/xml/root/Servers/Server")
    # Print results
    foreach($o in $n) { write-host "server" $o.ip "->" $o.website }
    server 10.2.2.1 -> abc
    
    # Negative test case
    $n=$doc.SelectNodes("/xml/root/Servers/Srvr")
    $n.Count
    0
    

    【讨论】:

      猜你喜欢
      • 2016-12-05
      • 2017-10-11
      • 1970-01-01
      • 2011-05-03
      • 1970-01-01
      • 2017-07-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多