简体   繁体   中英

Uncomment xml node using batch file or powershell

How can I uncomment a node in XML file using command prompt with powershell or simple batch file.

<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

here is the solution to uncomment an xml element passed as XPATH :

first get all comments from Xpath parent, then identify the right one by finding match on XPath child string.

build another node containing that $xmlNode without comments tag, replace $xmlNode with the child of that new node.

a bit tricky, i didn't find any other solution (plain text is not a solution)

# 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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