【问题标题】:Ignore prefix from XML file while removing tag删除标签时忽略 XML 文件中的前缀
【发布时间】:2016-09-06 07:14:19
【问题描述】:

我有一个 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>

然后它不会删除标签,但会收到如下错误

使用“1”参数调用“SelectNodes”的异常:“命名空间管理器或
需要 XSltContext。此查询具有前缀、变量或用户定义的函数。”
在行:2 字符:5
+ $Doc.ChildNodes.SelectNodes($_)
+ ------------------
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationExeption
    + FullyQualllifiedErrorId : DotNetMethodException

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

【问题讨论】:

  • 您不能忽略它,因为它是 XML 数据的一部分。此外,错误消息已经告诉您需要做什么:使用namespace manager

标签: xml powershell


【解决方案1】:

试试这个。

它将删除所有匹配输入值的节点。

# 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-30
    • 1970-01-01
    • 1970-01-01
    • 2011-02-17
    • 1970-01-01
    • 1970-01-01
    • 2021-04-26
    • 1970-01-01
    相关资源
    最近更新 更多