使用 Powershell 在具有命名空间的 XML 中使用 Xpath 选择属性 [英] Select an attribute with Xpath in a XML with namespace using Powershell
问题描述
我有一个 .Net 配置文件,里面有一个 NLog 节点:
I have a .Net config file with a NLog node inside:
<?xml version="1.0"?>
<configuration>
<appSettings>
</appSettings>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets async="true">
<target xsi:type="File" name="f" fileName="path to file" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="c,f" />
</rules>
</nlog>
</configuration>
我正在尝试使用 Powershell 更改 target
的 fileName
值.
I'm trying to change the target
's fileName
value using Powershell.
我正在使用此代码:
[xml]$xml = Get-Content $file
$ns = New-Object System.Xml.XmlNamespaceManager($xml.NameTable)
$ns.AddNamespace("ns", $namespace) # $namespace is `http://www.nlog-project.org/schemas/NLog.xsd`
$values = $xml.selectNodes($xpath, $ns)
我的 XPath 表达式是 //ns:nlog/ns:targets/ns:target[@ns:name='f']/@ns:fileName
My XPath expression is //ns:nlog/ns:targets/ns:target[@ns:name='f']/@ns:fileName
但是 $values 总是有 0 个结果.
But $values always has 0 results.
有什么想法吗?我做错了什么?
Any idea ? What am I doing wrong ?
谢谢!
推荐答案
在您的 XML 文档中,有一个默认命名空间:
In your XML document, there is a default namespace:
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd">
后代元素然后隐式地以这个命名空间为前缀.但是,属性不采用默认命名空间.换句话说,输入 XML 中的属性不称为ns:fileName
,而只是fileName
.这同样适用于 name
属性.
Descendant elements are then implicitly prefixed with this namespace. However, attributes do not take on a default namespace. In other words, the attribute in your input XML is not called ns:fileName
, but only fileName
. The same applies to the name
attribute.
//ns:nlog/ns:targets/ns:target[@name='f']/@fileName
根据 XML 的结构(及其可预测性),您可能希望将表达式缩短为
Depending on the structure of your XML (and its predictability) you might want to shorten the expression to
//ns:target[@name='f']/@fileName
<小时>
为了使您的初始 XPath 表达式起作用,输入的 XML 必须如下所示:
To make your intial XPath expression work, the input XML would have to look like:
<targets xmlns:ns="http://www.nlog-project.org/schemas/NLog.xsd" async="true">
<target xsi:type="File" ns:name="f" ns:fileName="path to file" />
</targets>
这篇关于使用 Powershell 在具有命名空间的 XML 中使用 Xpath 选择属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!