PowerShellでo:xmlを読み取る方法は?

Nov 05 2020

次の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>

前もって感謝します!

回答

2 mklement0 Nov 05 2020 at 14:56

PowerShellの便利なプロパティベースのXMLDOMの適応は、基本的に名前空間を無視するという事実を利用できます。これにより、修飾されていない要素名で目的の要素にドリルダウンできます。

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

対照的に、XPathベースのSelect-Xmlコマンドレット名前空間に対応しているため、明示的な名前空間の処理が必要です。または、Mathias R. Jessenの回答にlocal-name()示されているように、関数による回避策が必要です。

適切な名前空間処理を使用する場合(最終的にはより堅牢ですが、常に必要というわけではありません)、次を使用します。

(
  Select-Xml '//o:url' file.xml -Namespace @{ o='urn:schemas-microsoft-com:office:office' }
).Node.InnerText
  • @{ ... }使用される名前空間プレフィックスとURLを宣言するハッシュテーブル()を渡す必要があることに注意してください。これはo:、XPathクエリでプレフィックス(この場合は)を使用できるようにするための前提条件です。

    • プレフィックス名は、-Namespace引数と一致し、元のURLにマップされている限り、元の名前と一致する必要はありません。
  • Select-Xml一致したインスタンスのラッパーオブジェクトを返すSystem.Xml.XmlNodeため.Node、後者にアクセスする必要.InnerTextがあり、ノードのテキストコンテンツを返します。

    • 余談ですが、このアクセスの必要性.Nodeは不便XmlNodeです。一般的な使用例は、唯一のことを気にすることだからです。GitHubの提案#13669は
      -RawXmlNodeインスタンスを直接戻すスイッチを介して痛みを和らげようとしています。
1 MathiasR.Jessen Nov 05 2020 at 14:43

あなたが使用することができます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"

1 AdminOfThings Nov 05 2020 at 15:00

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'