删除标记

时间:2016-09-06 07:14:19

标签: xml powershell

我有一个PowerShell脚本,用于从XML文件中删除某些标记:

$Output = "C:\Users\Desktop\Resulttask.xml"

# Load the existing document
$Doc = [xml](Get-Content -Path C:\Users\Desktop\Test.xml)

# Specify tag names to delete and then find them
$DeleteNames = "Total" | ForEach-Object { 
    $Doc.ChildNodes.SelectNodes($_)
} | ForEach-Object {
    $Doc.ChildNodes.RemoveChild($_)
}

$Doc.Save($Output)

我的问题是它可以使用标准的XML文件,例如:

<html>
<body>b</body>
<Price>300</Price>
<Total>5000</Total>
</html>

但问题是XML文件必须从包含多个前缀的标记中删除标记,如。

<ns:html xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns="2" release="1">
  <ns:body>b</ns:body>
  <ns:Price>300</ns:Price>
  <ns:Total>5000</ns:Total>
</ns:html>

然后它不会删除标记,但会出现如下错误

Exception calling "SelectNodes" with "1" argument(s): "Namespace Mangager or
XSltContext needed. This query has a prefix, variable, or user-defined function."
At line:2  char:5
+     $Doc.ChildNodes.SelectNodes($_)
+     -------------------------------
    + CategoryInfo           : NotSpecified: (:) [], MethodInvocationExeption
    + FullyQuallifiedErrorId : DotNetMethodException

Error message in Powershell

我的问题是如何确保PowerShell命令忽略前缀ns:

1 个答案:

答案 0 :(得分:0)

试试这个。

它将删除所有加工输入值的节点。

# input is an array of values to delete
param([String[]] $values)

# Load the existing document
$xml = [xml](Get-Content -Path  D:\Temp\newtask.xml)

# Loop throug the input list
foreach ($value in $values) {

    # Set the namespace prefix
    $ns = New-Object System.Xml.XmlNamespaceManager($xml.NameTable)
    $ns.AddNamespace("ns", $xml.DocumentElement.NamespaceURI)

    # Get all nodes matching the input value
    $nodes =  $xml.SelectNodes("//*") | Where-Object { ($_.Name -eq "$value")}

    # in case there are multiple nodes matching the input value
    foreach ($node in $nodes )  {

        # Move to the parent node to remove the child.
        $node.ParentNode.RemoveChild($node)
    }
}

# Save the result in a different file so you can compare the files.
$filename = 'D:\Temp\newtask_result.xml'
$xml.save($filename)

像这样调用脚本

PS D:\temp> .\RemoveXmlElement.ps1 -values ns:Price,ns:Total