这是我的示例xml数据。如果有任何语法错误或某些xml缺失功能,请忽略。 任务是评论上述部分并取消评论以下部分。
<?xml version="1.0" encoding="UTF-8"?>
<providersbeans xmlns="http://www.springframework.org/schema/providers"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:dns="http://www.springframework.org/schema/dns"
xsi:schemaLocation="http://www.springframework.org/schema/dns/spring-dns.xsd">
<!-- COMMENT THIS SECTION -->
<dns:auth-head alias="authHead">
<dns:user-generator>
<dns:user-data>
<!-- USER AA -->
<dns:user name="AA"
password="AAAAAAAAAAAAAAAA" role="ROLE_AA" />
<!-- USER BB -->
<dns:user name="BB"
password="XXXXXXXXXXXXXXX" role="ROLE_BB" />
</dns:user-data>
</dns:user-generator>
</dns:auth-head>
<!-- UNCOMMENT THIS SECTION-->
<!--
<bean id="authHead" class="org.xx.providers">
<property name="providers">
<list>
<ref bean="AuthProvider"/>
</list>
</property>
</bean>
-->
</providersbeans>
我尝试了一些解决方案,但因为它有一个前缀而无法取得成功。 我为评论而修改的代码之一是:
$getxmlpath='C:\Powershell\securityfile.xml'
$xml=[xml](Get-Content $getxmlpath)
$xml.SelectNodes("//auth-head") | ForEach-Object # used with prefix as well, but didnt work
{
$var= $_;
$mycomment = $xml.CreateComment($var.OuterXml);
$var.ParentNode.ReplaceChild($mycomment , $var);
}
$xml.Save($getxmlpath);
答案 0 :(得分:1)
这样的事可能有用:
[xml]$xml = Get-Content 'C:\Powershell\securityfile.xml'
# create namespace manager
$nsm = New-Object Xml.XmlNamespaceManager($xml.NameTable)
$nsm.AddNamespace('dns', $xml.DocumentElement.dns)
# remove nested comments from <auth-head> node(s)
($xml.SelectNodes('//dns:auth-head//comment()', $nsm)) | % {
[void]$_.ParentNode.RemoveChild($_)
}
# comment-out node(s)
($xml.SelectNodes('//dns:auth-head', $nsm)) | % {
$comment = $xml.CreateComment($_.OuterXml)
[void]$_.ParentNode.ReplaceChild($comment, $_)
}
# uncomment <bean> node(s)
($xml.SelectNodes('//comment()')) | ? {
$_.InnerText -like '*<bean*'
} | % {
$newxml = [xml]$_.InnerText
$node = $xml.ImportNode($newxml.DocumentElement, $true)
$node.SetAttribute('xmlns', $xml.DocumentElement.NamespaceURI)
[void]$_.ParentNode.ReplaceChild($node, $_)
}
我没有找到重新插入<bean>
节点的方法而没有获得explict(空)命名空间属性(xmlns=""
),因此我将该属性设置为默认命名空间XML文档。
请注意,您必须删除(或以其他方式修改)您要注释掉的节点的嵌套注释。否则,第一个嵌套注释中的结束-->
会过早地终止注释节点,从而使您的XML结构无效:
<!--dns:auth-head alias="authHead">
<dns:user-generator>
<dns:user-data>
<!-- USER AA --> # XML comment ends here!
<dns:user name="AA"
password="AAAAAAAAAAAAAAAA" role="ROLE_AA" />
<!-- USER BB -->
<dns:user name="BB"
password="XXXXXXXXXXXXXXX" role="ROLE_BB" />
</dns:user-data> # tags from here on are invalid, because
</dns:user-generator> # they're missing their respective opening tag
</dns:auth-head-->