这是一个用于注释 xml 节点的 powershell 函数:
function CommentXmlNode([String] $filePath, [String] $nodeXPath)
{
[xml]$xml = Get-Content -Path "$filePath"
# Find the nodes that we want to comment
$xml.SelectNodes("$nodeXPath") | ForEach-Object {
$nodeToComment = $_;
$comment = $xml.CreateComment($nodeToComment.OuterXml);
# Comment the node
$nodeToComment.ParentNode.ReplaceChild($comment, $nodeToComment);
}
# Save the file
$xml.Save("$filePath");
}
这是取消注释 xml 节点的 powershell 函数:
function UncommentXmlNode([String] $filePath, [String] $searchCriteria)
{
[xml]$xml = Get-Content -Path "$filePath"
# Find all comments on the xml file
$xml.SelectNodes("//comment()") | ForEach-Object {
# We convert the comment to an xml
$nodeToConvert = $_;
$convertedNode = $nodeToConvert.InnerText | convertto-xml
[xml]$xmlConvertedNode = $convertedNode
# Find the comment that match our search criteria
$xmlConvertedNode.SelectNodes("/descendant::*[contains(text(), '$searchCriteria')]") | ForEach-Object {
$nodeToUncomment = $_;
$strToFind = "<!--" + $nodeToUncomment.InnerText + "-->"
$strReplacement = $nodeToUncomment.InnerText
# Replace the commented string with uncommented one
$con = Get-Content "$filePath"
$con | % { $_.Replace($strToFind, $strReplacement) } | Set-Content "$filePath"
}
}
}
你可以像这样使用它们:
CommentXmlNode "D:\temp\file.xml" "YourXPath"
--
UncommentXmlNode "D:\temp\file.xml" "Some String in the xml node to Uncomment"