我想在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>
2条答案
按热度按时间irlmq6kh1#
不幸的是,为了达到这个目标,你必须直面命名空间问题:
mm5n2pyu2#
您有一个命名空间问题。使用Xml Linq