繁体   English   中英

如何使用 powershell 读取 o:xml?

[英]How to read o:xml with powershell?

我有以下 xml 文件,但不知道如何使用 Powershell 读取它,有人可以帮忙吗? 谢谢!

我需要从 Powershell 获取 url 值。

<o:OfficeConfig xmlns:o="urn:xxx:xxx:xxx">
<o:services>
<o:service o:name="xxxx">
<o:url>https://xxx.xxx</o:url>
</o:service>
</o:services>
</o:OfficeConfig>

提前致谢!

您可以利用 PowerShell 方便、基于属性的 XML DOM 适配这一事实本质上忽略命名空间,从而允许您通过非限定元素名称简单地深入到感兴趣的元素:

([xml] (Get-Content -Raw file.xml)).OfficeConfig.services.service.url

相比之下,基于 XPath 的Select-Xml cmdlet命名空间感知的,因此需要显式命名空间处理 - 或通过local-name()函数的解决方法,如Mathias R. Jessen 的回答所示

如果您想使用正确的命名空间处理 - 这最终更健壮,但并非总是必要的 - 使用以下内容:

(
  Select-Xml '//o:url' file.xml -Namespace @{ o='urn:schemas-microsoft-com:office:office' }
).Node.InnerText
  • 请注意,需要传递一个哈希表( @{ ... } )来声明所使用的命名空间前缀和 URL,这是能够在 XPath 查询中使用前缀(在本例中为o: )的先决条件。

    • 前缀名称不需要与原始名称匹配,只要它们与-Namespace参数一致并映射到原始 URL。
  • Select-Xml返回匹配的System.Xml.XmlNode实例周围的包装对象,因此需要.Node访问后者,然后.InnerText返回节点的文本内容。

    • .Node :这种需要访问.Node是不方便的,因为典型的用例是只关心XmlNode GitHub 建议 #13669试图通过
      -Raw直接返回XmlNode实例的-Raw开关。

您可以使用Select-Xml

$rawXml = @'
<o:OfficeConfig xmlns:o="urn:schemas-microsoft-com:office:office">
<o:services>
<o:service o:name="GetFederationProvider">
<o:url>https://odc.officeapps.live.com/odc/emailhrd/getfederationprovider</o:url>
</o:service>
</o:services>
</o:OfficeConfig>
'@ 

$urlNode = $rawXml |Select-Xml -XPath '//*[local-name() = "url"]' |Select -Expand Node
$url = $urlNode.innerText

$url现在将包含字符串"https://odc.officeapps.live.com/odc/emailhrd/getfederationprovider"

由于您要返回 json,因此您可以将 json 转换为 PowerShell 对象:

$configServiceUrl = "https://officeclient.microsoft.com/config16processed?rs=en-us&build=16.0.7612"
$headers = @{'Accept' = 'application/json'}
$getFederationProviderEndpoint = Invoke-WebRequest -Uri "$($configServiceUrl)&services=GetFederationProvider" -Headers $headers -Method GET

$obj = $getFederationProviderEndpoint.Content | ConvertFrom-Json
$obj.'o:officeconfig'.'o:services'.'o:service'.'o:url'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM