如何从Powershell中的Xml Document中选择单个节点,其中XPath包含变量?

时间:2013-11-17 22:25:53

标签: xml powershell xpath

在Powershell中操作XML文件时,我正试图检测一个节点是否已经存在。

不幸的是,我正在处理的XmlDocument使用默认命名空间,我认为这会混淆一些东西。

这是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>

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

添加它很好(除了一些命名空间的恶作剧)但是检测它让我感到难过。

这是我到目前为止所尝试的内容:

# 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"
}

我一直在尝试各种不同的方法。任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:3)

似乎这应该有效:

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