Powershell XML阅读带标记的节点

64jmpszr  于 2023-05-17  发布在  Shell
关注(0)|答案(2)|浏览(95)

我想在XML中现有的<project/files>节点中添加一个新节点<executables>。为此,我编写了以下代码:

# Load the XML file into the XmlDocument object
$xml = New-Object System.Xml.XmlDocument
$xml.Load("C:\path\to\file.xml")

# Select the parent node where you want to add the new node
$parent = $xml.SelectSingleNode("//project/files")

# Create a new node under the parent node
$newNode = $xml.CreateElement("executables")

# Add content to the new node
$content = $xml.CreateTextNode("C:\executable.exe")
$newNode.AppendChild($content)

# Add the new node to the parent node
$parent.AppendChild($newNode)

# Save the changes to the XML file
$xml.Save("C:\path\to\file.xml")

然而,代码似乎不起作用,因为变量$parent在调用函数$xml.SelectSingleNode("//parent/node")后具有$null的值:

# Select the parent node where you want to add the new node
$parent = $xml.SelectSingleNode("//parent/node")

但是,如果我从XML文件的<project>节点中删除所有XML命名空间,那么上面的代码就可以工作。我想忽略标记,只加载<project>,而不必指定XML命名空间,因为XML命名空间的内容可能会随着XML文件的不同而改变。这可能吗?
XML文件不工作:

<?xml version="1.0"?>
    <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.google.com/" xmlns="http://www.google.com/apx" version="22.04" build="11114914" target="targetArchitecture">
      <files>
        <executables>C:\executable.exe</executables>
      </files>
    </project>

工作XML文件:

<?xml version="1.0"?>
<project>
  <files>
    <executables>C:\executable.exe</executables>
  </files>
</project>
irlmq6kh

irlmq6kh1#

不幸的是,为了达到这个目标,你必须直面命名空间问题:

#declare your default namespace
$ns = New-Object System.Xml.XmlNamespaceManager($xml.NameTable)
$ns.AddNamespace("xx", "http://www.google.com/apx")

#now search for $parent properly using the default namespace
$parent = $xml.SelectNodes('//xx:files',$ns)

#create the new node; note that the 2nd argument is necessary in order
#to suppress the inclusion of an empty xmlns "attribute" in the new node
$newNode = $xml.CreateElement("executables", "http://www.google.com/apx")

# From here, it's the same: Add content to the new node
$content = $xml.CreateTextNode("C:\executable.exe")
$newNode.AppendChild($content)
# Add the new node to the parent node
$parent.AppendChild($newNode)
mm5n2pyu

mm5n2pyu2#

您有一个命名空间问题。使用Xml Linq

using assembly System.Xml.Linq

$inputFilename = 'c:\temp\test.xml'
$outputFilename = 'c:\temp\test1.xml'

$doc = [System.Xml.Linq.XDocument]::Load($inputFilename)

$project = $doc.Root
$ns = $project.GetDefaultNamespace()

$files = $project.Element($ns + 'files')

$executables = [System.Xml.Linq.XElement]::new($ns + [System.Xml.Linq.XName]::Get('executables'), 'C:\executable.exe')
$files.Add($executables)

$doc.Save($outputFilename)

相关问题