繁体   English   中英

使用批处理文件或Powershell取消注释xml节点

[英]Uncomment xml node using batch file or powershell

如何使用Powershell或简单批处理文件的命令提示符取消注释XML文件中的节点。

<Settings> 
<SettingNode name="Installation">
<SettingNode name="Features">
      <Setting name="Features" scope="Installation">
        <StringArray>
            <!-- Uncomment the below line to activate the required features for the Pilot Version-->
            <!--<String>PilotVersion</String>-->
            <String>GlobalSearchAndReplace</String>
        </StringArray>
      </Setting>
    </SettingNode>
</SettingNode>
</Settings>

您可以将xml视为纯文本,然后使用replace cmdlet:

(gc c:\files\test.xml) -replace "<!--<String>PilotVersion</String>-->","<String>PilotVersion</String>"  # |sc c:\files\test.xml if you xant to save the file

这是取消注释作为XPATH传递的xml元素的解决方案:

首先从Xpath父级获取所有注释,然后通过在XPath子字符串上找到匹配项来确定正确的注释。

构建包含该$ xmlNode且不带注释标签的另一个节点,将$ xmlNode替换为该新节点的子节点。

有点棘手,我没有找到其他解决方案(纯文本不是解决方案)

# path to the file
$File = "c:\pathtoyourfile\example.xml"

# XPath to the element to un comment
$XPath = "/Settings/SettingNode[@name='Installation']/SettingNode[@name='Features']/Setting[@name='Features' and @scope='Installation']/StringArray/String"

# get xml file
$xmlFile = [xml](Get-Content $File) 

# get parent and child path from XPath
$parentXPath = $XPath.Substring(0, $XPath.LastIndexOf('/'))
$childXPath = $XPath -replace "$parentXPath/", ''

# get comment
$xmlNode = $xmlFile.SelectNodes("$parentXPath/comment()") | ? { $_.InnerText -match "<$childXPath" }

# create node containing comment content
$tempNode = $xmlFile.CreateElement("tempNode")          
$tempNode.InnerXml = $xmlNode.Value
$replaceNode = $tempNode.SelectSingleNode("/$childXPath")

# process replacement 
$xmlNode.ParentNode.ReplaceChild($replaceNode, $xmlNode)

# save change
$xmlFile.Save($File)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM