我需要创建这个 XML:
<?xml version="1.0" encoding="UTF-8"?>
<SRP xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="sample.xsd">
..但是虽然我知道如何使用 XMLWriter 编写命名空间(例如:
$XmlWriter.WriteAttributeString("xmlns", "xsi",
"http://www.w3.org/2000/xmlns/",
"http://www.w3.org/2001/XMLSchema-instance");
..我一直无法在变量中这样做:
[xml]$XML = New-Object System.Xml.XmlDocument
$Declaration=$XML.CreateXmlDeclaration("1.0","UTF-8",$Null)
$XML.AppendChild($Declaration)
我已经尝试了 Namespacemanager 的各种组合,但无济于事。这似乎是一个愚蠢的问题,但到目前为止我一直无法复制它(除了使用带有硬编码 XML 的此处字符串并将其转换为当然是 XML,但我更愿意以“正确”的方式来做 :)
感谢到目前为止阅读的所有人:)
最佳答案
为此您不需要 namespace 管理器。只需使用正确的命名空间创建节点/属性,然后让 XML 处理器确定将它们放在哪里。
以你的例子为例:
$x = New-Object Xml.XmlDocument
$x.AppendChild($x.CreateXmlDeclaration("1.0","UTF-8",$null))
$node = $x.CreateElement("SRP")
$attr = $x.CreateAttribute("xsi","noNamespaceSchemaLocation","http://www.w3.org/2001/XMLSchema-instance")
$attr.Value="schema.xsd"
$node.SetAttributeNode($attr)
$x.AppendChild($node)
$x.OuterXml
关于xml - Powershell - 创建具有特定命名空间的 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46298443/