我碰到一堵砖墙,试图在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'

关于xml - 如何从XPath包含变量的Powershell中的Xml文档中选择单个节点?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20036992/

10-11 02:28