【发布时间】:2020-06-09 03:14:35
【问题描述】:
我正在尝试创建一个函数来获取名称空间管理器,但我收到一条消息错误并且不明白为什么。
function Get-XmlNamespaceManager([ xml ]$xml, [string]$NamespaceURI = "")
{
if ([string]::IsNullOrEmpty($NamespaceURI)) { $NamespaceURI = $xml.DocumentElement.NamespaceURI }
[System.Xml.XmlNamespaceManager]$xmlNsManager = New-Object System.Xml.XmlNamespaceManager($xml.NameTable)
$xmlNsManager.AddNamespace("ns", $NamespaceURI)
return ,$xmlNsManager
}
以下消息:
New-Object : A constructor was not found. Cannot find an appropriate constructor for type System.Xml.XmlNamespaceManager.
At C:\Scripts\Add Archive Handle\Add_Archive_Handle.ps1:35 char:53
+ ... NsManager = New-Object System.Xml.XmlNamespaceManager($xml.NameTable) ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (:) [New-Object], PSArgumentException
+ FullyQualifiedErrorId : CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand
但我的 $xmlNsManager 返回:
PS C:\Path\To\Myfiles> $xmlNsManager
xmlns xml ns
感谢您的帮助。
这是我的代码的一部分:
Get-ChildItem -Path 'C:\Scripts\Add Archive Handle\Source\' -Recurse -Include "*.imdi" -File | ForEach-Object {
$NodePath = $xml.METATRANSCRIPT.Session.Resources.MediaFile.ResourceLink,$xml.METATRANSCRIPT.Session.Resources.WrittenResource.ResourceLink
[xml]$xml = Get-Content $_.FullName;
$xml= $xml.METATRANSCRIPT.OuterXml;
$xmlAtt = $xml.CreateAttribute("ArchiveHandle")
$dt = $xml.METATRANSCRIPT.Attributes.GetNamedItem('Date')
$xmlAtt = $xml.METATRANSCRIPT.Attributes.InsertBefore($xmlAtt, $dt);
function Get-XmlNamespaceManager([ xml ]$xml, [string]$NamespaceURI =""){
if ([string]::IsNullOrEmpty($NamespaceURI)) { $NamespaceURI = $xml.DocumentElement.NamespaceURI }
[System.Xml.XmlNamespaceManager]$xmlNsManager =New-Object System.Xml.XmlNamespaceManager($xml.NameTable)
$xmlNsManager.AddNamespace("ns", $NamespaceURI)
return ,$xmlNsManager }
function Get-FullyQualifiedXmlNodePath([string]$NodePath, [string]$NodeSeparatorCharacter = '.'){
return "/ns:$($NodePath.Replace($($NodeSeparatorCharacter), '/ns:'))"}
function Get-XmlNode([ xml ]$xml, [string]$NodePath, [string]$NamespaceURI = "", [string]$NodeSeparatorCharacter = '.'){
$xmlNsManager = Get-XmlNamespaceManager -XmlDocument $xml -NamespaceURI $NamespaceURI
[string]$fullyQualifiedNodePath = Get-FullyQualifiedXmlNodePath -NodePath $NodePath -NodeSeparatorCharacter $NodeSeparatorCharacter
$node = $xml.SelectSingleNode($fullyQualifiedNodePath, $xmlNsManager)
return $node}}
【问题讨论】:
标签: xml powershell