【问题标题】:Powershell insert XML here-string into xml documentPowershell 将 XML here-string 插入 xml 文档
【发布时间】:2021-09-27 16:53:00
【问题描述】:

我正在尝试将 XML here-string 插入 XML 文档。但是,保存的 XMLdoc 显示:“System.Xml.XmlDocument”,而不是内容。我该如何解决这个问题?

[xml] $Doc = New-Object System.Xml.XmlDocument

$updateNode = [xml] "<Update>                       
                          <Request>Test</Request>
                     </Update>"

#Create XML declaration
$declaration = $Doc.CreateXmlDeclaration("1.0","UTF-8",$null)

#Append XML declaration
$Doc.AppendChild($declaration)
    
#Create root element
$root = $Doc.CreateNode("element","BrowseDetailsRequest",$null)

#Create node based on Here-String
$node = $Doc.CreateElement("element",$updateNode,$null)

#Append node
$root.AppendChild($node)
    
#Append root element
$Doc.AppendChild($root)   

此时输出:

<?xml version="1.0" encoding="UTF-8"?>
<BrowseDetailsRequest>
  <System.Xml.XmlDocument />
</BrowseDetailsRequest>

【问题讨论】:

  • 问题是“CreateElement()”不接受 XML 数据类型(第二个参数)。第二个参数是string localName,它是新元素的本地名称。看CreateElement()的签名public virtual System.Xml.XmlElement CreateElement (string? prefix, string localName, string? namespaceURI);docs.microsoft.com/en-us/dotnet/api/…

标签: powershell xmldocument xmlnode


【解决方案1】:

您并没有真正操纵 xml 中的文本。使用对象来操作 xml。所以你需要为更新和请求创建一个元素,然后分配请求的内部文本值。

$Doc = New-Object System.Xml.XmlDocument
$declaration = $Doc.CreateXmlDeclaration("1.0","UTF-8",$null)
$Doc.AppendChild($declaration)
$root = $Doc.CreateNode("element","BrowseDetailsRequest",$null)
$elUpdate = $doc.CreateElement("element","Update",$null)
$elRequest = $doc.CreateElement("element","Request",$null)
$elRequest.InnerText = "Test"
$elUpdate.AppendChild($elRequest)
$root.AppendChild($elUpdate)
$doc.AppendChild($root)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-08
    • 2022-07-11
    • 1970-01-01
    • 1970-01-01
    • 2014-09-18
    • 2023-04-08
    相关资源
    最近更新 更多