xml - Powershell - 创建具有特定命名空间的 XML

标签 xml powershell

我需要创建这个 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/

相关文章:

html - 在执行 TEI 时,无法让首字下沉的 css 跨度类起作用。它既不验证也不工作

string - Powershell - $args 去除逗号

powershell - 使用 Powershell RM 列出 Azure 应用服务的实例

powershell - select-object -expandproperty with null 属性

sql - 从 Oracle 数据库中的 XML 属性查询时如何使用 XPath 表达式

java - 错误:(41) Error parsing XML: not well-formed (invalid token) + cannot resolve the symbol R

powershell - 从 PowerShell 执行外部命令不接受参数

powershell - 获取事件目录组的成员数?

android - 来自 findViewById 的 NullPointer 错误

xml - xpath 查询在使用大于和小于时返回错误值?