如何使用 powershell 读取 o:xml? [英] How to read o:xml with powershell?
问题描述
我有以下 xml 文件,但不知道如何使用 Powershell 读取它,有人可以帮忙吗?谢谢!
I have following xml file but don't know how to read it with Powershell, Anyone can help with? Thanks!
我需要从 Powershell 获取 url 值.
I need to get the url value from Powershell.
<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 的改编 本质上忽略 命名空间,允许您通过不合格的元素名称简单地深入到感兴趣的元素:
You can take advantage of the fact that PowerShell's convenient, property-based adaptation of the XML DOM essentially ignores namespaces, allowing to you simply drill down to the element of interest by the unqualified element names:
([xml] (Get-Content -Raw file.xml)).OfficeConfig.services.service.url
相比之下,基于 XPath 的 Select-Xml
cmdlet 是 命名空间感知,因此需要显式命名空间处理 - 或通过 local-name()
函数的解决方法,如Mathias R. Jessen 的回答中显示.
By contrast, the XPath-based Select-Xml
cmdlet is namespace-aware, and therefore requires explicit namespace handling - or a workaround via the local-name()
function, as shown in Mathias R. Jessen's answer.
如果您想使用正确的命名空间处理 - 这最终会更健壮,但并非总是必要的 - 请使用以下内容:
If you want to use proper namespace handling - which is ultimately more robust, but not always necessary - use the following:
(
Select-Xml '//o:url' file.xml -Namespace @{ o='urn:schemas-microsoft-com:office:office' }
).Node.InnerText
注意需要传递一个哈希表 (
@{ ... }
) 来声明所使用的命名空间前缀和 URL,这是能够使用前缀 (o:
,在本例中)在 XPath 查询中.Note the need to pass a hashtable (
@{ ... }
) that declares the namespace prefixes and URLs used, which is the prerequisite for being able to use the prefixes (o:
, in this case) in the XPath query.- 前缀名称不需要与原始名称匹配,只要它们与
-Namespace
参数一致并映射到原始 URL 即可.
- The prefix names need not match the ones in the original, as long as they're consistent with the
-Namespace
argument and are mapped to the original URLs.
Select-Xml
返回匹配的System.Xml.XmlNode
实例,所以需要.Node
访问后者,和.InnerText
然后返回节点的文本内容.Select-Xml
returns wrapper objects around the matchedSystem.Xml.XmlNode
instances, so.Node
is required to access the latter, and.InnerText
then returns the node's text content.- 顺便说一句:这种需要访问
.Node
是不方便的,因为典型的用例是只关心XmlNode
;GitHub 建议 #13669 旨在通过
减轻痛苦-Raw
开关,直接返回XmlNode
实例.
- As an aside: This need to access
.Node
is inconvenient, as the typical use case is to care about theXmlNode
only; GitHub suggestion #13669 seeks to ease the pain via a
-Raw
switch that returs theXmlNode
instances directly.
这篇关于如何使用 powershell 读取 o:xml?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- 前缀名称不需要与原始名称匹配,只要它们与