Skip to main content
 首页 » 编程设计

xml之如何从XPath包含变量的Powershell中的Xml文档中选择单个节点

2025年05月04日57pengyingh

我碰到一堵砖墙,试图在Powershell中处理XML文件时检测节点是否已经存在。

不幸的是,我正在处理的XmlDocument使用默认的 namespace ,我认为这会使事情感到困惑。

这是XML的子集

<?xml version="1.0" encoding="utf-8"?> 
<Configuration xmlns="http://www.sdltridion.com/2009/GUI/Configuration" xmlns:ext="http://www.sdltridion.com/2009/GUI/extensions" xmlns:cmenu="http://www.sdltridion.com/2009/GUI/extensions/ContextMenu"> 
    <editor name="MyExtension"> 
      <installpath xmlns="http://www.sdltridion.com/2009/GUI/Configuration">C:\Program Files (x86)\Tridion\web\WebUI\Editors\MyExtension</installpath> 
      <configuration xmlns="http://www.sdltridion.com/2009/GUI/Configuration">Editor\Configuration\editor.config</configuration> 
      <vdir xmlns="http://www.sdltridion.com/2009/GUI/Configuration">MyExtension</vdir> 
    </editor> 
  </editors> 
</Configuration> 

我想检查名称属性设置为“MyExtension”的编辑器节点在Powershell中是否存在,如果不存在,请添加它。

添加它很好(除了一些命名空间的恶作剧),但检测到它让我很困惑。

到目前为止,这是我尝试过的方法:
# Update System.config 
$filename = $tridionInstallLocation + '\web\WebUI\WebRoot\Configuration\System.config' 
$conf = [xml](gc $filename) 
 
[System.Xml.XmlNamespaceManager] $nsm = new-object System.Xml.XmlNamespaceManager $conf.NameTable 
$nsm.AddNamespace("x", "http://www.sdltridion.com/2009/GUI/Configuration") 
 
# Editor 
$xpath = "//x:Configuration/x:editors/x:editor[name=MyExtension]" 
# $existingModelNode = $conf.SelectSingleNode($xpath, $nsm) 
$existingModelNode = Select-Xml $conf -XPath $xpath 
Write-Host $existingEditorNode # This is blank always 
if($existingEditorNode -eq $null) 
{ 
    $editors = [System.Xml.XmlElement]$conf.Configuration.editors 
    $myElement = $conf.CreateElement("editor", $nsm.LookupNamespace("x")) 
    $nameAttr = $myElement.SetAttribute("name", $name) 
    $myElement.InnerXml = "<installpath xmlns='http://www.sdltridion.com/2009/GUI/Configuration'>" + $editorInstallLocation + "</installpath><configuration xmlns='http://www.sdltridion.com/2009/GUI/Configuration'>" + $editorConfigFile + "</configuration><vdir xmlns='http://www.sdltridion.com/2009/GUI/Configuration'>" + $name + "</vdir>" 
    $editors.AppendChild($myElement) 
} 
else 
{ 
    Write-Host "Editor node already exists in System.config with name $name, skipping" 
} 

我一直在尝试各种不同的方法。谁能帮我吗?

请您参考如下方法:

似乎这样应该可以工作:

@($config.Configuration.editors.editor.name) -contains 'MyExtension'