【发布时间】:2019-11-01 15:01:07
【问题描述】:
我正在尝试将 API 调用的结果输出到预定义的 XML 结构。我在 Powershell 中创建 XML 并添加声明和根节点。
我找到了如何在另一个 SO 条目中添加多个子节点的方法。太愚蠢了,我在写这篇文章之前关闭了这个标签,所以很抱歉我没有链接了。
正如您在下面看到的,根节点不是我查询的值需要去哪里的定义的一部分,它从根节点的下一层开始。
稍后其他项目也将添加到根节点。
我的设置方式,它与循环一起工作,当我注释行时添加我想要的节点:
#$xmlDocument.AppendChild($xmlRoot) | Out-Null
我确实得到了输出:
<?xml version="1.0" encoding="UTF-8"?><DEF><GHJ><GHJ /></GHJ></DEF>
看起来不错,但根元素(显然)丢失了,如果我添加该注释行,我会收到一条错误消息(从德语翻译)“文档已经有一个 'DocumentElement' 节点。”
预期输出
<?xml version="1.0" encoding="UTF-8"?><ABC xmlns:xsi="http://www.w3.org 2001/XMLSchema-instance" noNamespaceSchemaLocation="Dummy.xsd"><DEF><GHJ><GHJ /></GHJ></DEF></ABC>
(重复的 GHJ 是故意的)
$config = @{Output = @{Root = "ABC"}}
$targetSplit = ("DEF\GHJ\GHJ").Split("\")
# Create XML document
[xml]$xmlDocument = New-Object System.Xml.XmlDocument
# Create XML declaration
$xmlDeclaration = $xmlDocument.CreateXmlDeclaration("1.0","UTF-8",$null)
# Add declaration to XML document
$xmlDocument.AppendChild($xmlDeclaration)
# Create root node
$xmlRoot = $xmlDocument.CreateElement($config.Output.Root)
# Add root attributes
$xmlRoot.SetAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance')
$xmlRoot.SetAttribute('xsi:noNamespaceSchemaLocation', 'Dummy.xsd')
#add root to the document
#$xmlDocument.AppendChild($xmlRoot) | Out-Null
$lastXMLElement = $xmlDocument
for($i = 0; $i -lt $targetSplit.Length; $i++) {
$xmlElement = $xmlDocument.CreateElement($targetSplit[$i])
$lastXMLElement = $lastXMLElement.AppendChild($xmlElement)
}
$xmlDocument.OuterXml
【问题讨论】:
-
$lastXMLElement = $xmlDocument->$lastXMLElement = $xmlroot,否则你试图在文档的根目录添加多个节点:)
标签: xml powershell