【问题标题】:How to read XML file from web using powershell如何使用 powershell 从 Web 读取 XML 文件
【发布时间】:2010-12-21 14:50:47
【问题描述】:

当我使用 URL http://ilo-ip/xmldata?item=All 连接到我的 HP ILO 时,它会返回以下格式的 XML 文件。

  <?xml version="1.0" ?> 
- <RIMP>
- <HSI>
  <SPN>ProLiant DL385 G1</SPN> 
  <SBSN>ABCDEFG</SBSN> 
  <UUID>123456789</UUID> 
  </HSI>
- <MP>
  <ST>1</ST> 
  <PN>Integrated Lights-Out (iLO)</PN> 
  <FWRI>1.82</FWRI> 
  <HWRI>ASIC: 2</HWRI> 
  <SN>ILOABCDEFG</SN> 
  <UUID>ILO1234545</UUID> 
  </MP>
  </RIMP>

是否有任何 powershell 命令/脚本可以从 Web URL 读取 XML 数据?

【问题讨论】:

    标签: xml powershell


    【解决方案1】:

    PowerShell 使用 .Net 框架 XmlDocument,因此您可以调用 load 方法将 xml 加载到 XmlDocument 对象中,如下所示:

    #Option 1    
    $doc = New-Object System.Xml.XmlDocument
    $doc.Load("http://ilo-ip/xmldata?item=All")
    
    #Option 2
    [xml]$doc = (New-Object System.Net.WebClient).DownloadString("http://ilo-ip/xmldata?item=All")
    
    
    # Your XML will then be in the $doc and the names of the XML nodes can be used as
    # properties to access the values they hold. This short example shows how you would
    # access the value held in the SPN nodes from your sample XML 
    Write-Host $doc.RIMP.HSI.SPN
    

    如果您想了解有关在加载 XML 后使用它的更多信息,请查看 PowerShell.com 上的 Dr. Tobias Weltner's eBookchapter 14 涵盖了 XML。

    【讨论】:

    • 感谢您的回复。如何阅读加载的代码?我在互联网上找不到太多帮助。
    • XML 将保存在 $doc 对象中,因此您可以通过属性表示法访问它。例如 Write-Host $doc.RIMP.HSI.SPN 这会将“ProLiant DL385 G1”写入控制台。您可以做的是将 $doc 传递给 Get-Member 以获取属性列表,例如$文档 |获取会员
    • 嗨,艾伦,当您按照您的描述以两种方式加载 xml 时,我遇到了一个异常。例外是"The server committed a protocol violation. Section=ResponseStatusLine"
    • 嗨ѕтƒ,您是否能够在不使用 powershell 的情况下访问此 xml 文件?例如你能从你的网络浏览器打开它吗
    【解决方案2】:

    当然。您可以使用 .NET WebClient 对象从 Web 下载 XML,然后使用 [xml] 类型将字符串解释为 XML,如下所示:

    $url = "http://blogs.msdn.com/powershell/rss.xml"
    [xml]$xml = (new-object System.Net.WebClient).DownloadString($url)
    $xml.rss.channel | Foreach {$_.item} |
        Where {[DateTime]$_.pubDate -gt (Get-Date).AddMonths(-1)} |
        Format-Table Title
    

    【讨论】:

      猜你喜欢
      • 2014-01-18
      • 2010-11-19
      • 2011-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-14
      • 2017-03-16
      • 2019-10-07
      相关资源
      最近更新 更多