使用powershell有条件地删除xml中的child
我有一个使用powershell有条件地删除xml中的child,xml,powershell,Xml,Powershell,我有一个xml配置文件: <?xml version="1.0"?> <Tenant> <Tenants> <Tenant name="tenant_0" siteName="t100001" urlWebSite="qa.local" username="admin" password="admin" />
xml
配置文件:
<?xml version="1.0"?>
<Tenant>
<Tenants>
<Tenant name="tenant_0" siteName="t100001" urlWebSite="qa.local" username="admin" password="admin" />
<Tenant name="tenant_1" siteName="t100002" urlWebSite="qa.local" username="admin" password="admin" />
<Tenant name="tenant_2" siteName="t100003" urlWebSite="qa.local" username="admin" password="admin" />
<Tenant name="tenant_3" siteName="t100004" urlWebSite="qa.local" username="admin" password="admin" />
</Tenants>
<Tenant>
如果
childnode
具有siteName
属性,而该属性不在$siteName
数组中,我还需要从租户中删除childnode
。显示的xml无效,因为最后的
应该是一个结束标记:
解决了这个问题后,下面是修改后的代码:
# Best use below method to load an XML from file, because it automatically detects the file encoding
$config = New-Object System.XML.XMLDocument
$config.Load("path\xml.config")
$urlWebSite = 'prod.local'
$siteNames = 't100001','t100002','t100003' # don't need '@()' here. The comma is enough to create an array
foreach ($node in $config.Tenant.Tenants.Tenant) {
if ($siteNames -contains $node.siteName) {
# reset the attributes value
$node.SetAttribute('urlWebSite', $urlWebSite)
}
else {
# not in the $siteNames array, so remove this node
$null = $node.ParentNode.RemoveChild($node)
}
}
$config.save("path\xml.config")
输出:
<?xml version="1.0"?>
<Tenant>
<Tenants>
<Tenant name="tenant_0" siteName="t100001" urlWebSite="prod.local" username="admin" password="admin" />
<Tenant name="tenant_1" siteName="t100002" urlWebSite="prod.local" username="admin" password="admin" />
<Tenant name="tenant_2" siteName="t100003" urlWebSite="prod.local" username="admin" password="admin" />
</Tenants>
</Tenant>
您显示的xml无效,因为最后的
应该是结束标记:
解决了这个问题后,下面是修改后的代码:
# Best use below method to load an XML from file, because it automatically detects the file encoding
$config = New-Object System.XML.XMLDocument
$config.Load("path\xml.config")
$urlWebSite = 'prod.local'
$siteNames = 't100001','t100002','t100003' # don't need '@()' here. The comma is enough to create an array
foreach ($node in $config.Tenant.Tenants.Tenant) {
if ($siteNames -contains $node.siteName) {
# reset the attributes value
$node.SetAttribute('urlWebSite', $urlWebSite)
}
else {
# not in the $siteNames array, so remove this node
$null = $node.ParentNode.RemoveChild($node)
}
}
$config.save("path\xml.config")
输出:
<?xml version="1.0"?>
<Tenant>
<Tenants>
<Tenant name="tenant_0" siteName="t100001" urlWebSite="prod.local" username="admin" password="admin" />
<Tenant name="tenant_1" siteName="t100002" urlWebSite="prod.local" username="admin" password="admin" />
<Tenant name="tenant_2" siteName="t100003" urlWebSite="prod.local" username="admin" password="admin" />
</Tenants>
</Tenant>
为什么不使用内置的Powershell Xml cmdlet或Xml.Net名称空间来解析所需的Xml?为什么不使用内置的Powershell Xml cmdlet或Xml.Net名称空间来解析所需的Xml?