我正在寻找一个将字符串列表添加到XML对象的解决方案
这来自我需要调用的Web服务的文档:
fileNames:String列表指定多个文件名多个 必须使用fileNames参数,如下所示:
<!--1 or more repetitions:--> <xsd1:fileNames>test1.txt</xsd1:fileNames> <xsd1:fileNames>test2.txt</xsd1:fileNames>
不允许添加具有相同名称的第二个属性
$soap.Envelope.Body.sampleobject | Add-Member -MemberType Property -Name fileNamesList -Value $fileNames[0]
#This works fine
$soap.Envelope.Body.sampleobject | Add-Member -MemberType Property -Name fileNamesList -Value $fileNames[1]
#This fails with error message "Add-Member : Cannot add a member with the name "fileNamesList" because a member with that name already exists. "
如果可能的话,我想避免将SOAP对象作为字符串处理并插入字符串。
有一种优雅的方法可以使用PowerShell来管理它吗?
UPDATE 更多代码
$soap = [xml]@'
<Envelope>
<Body>
<sampleObject>
<Name>MySampleObject</Name>
</sampleObject>
</Body>
</Envelope>
'@
[string[]]$filenames='filea.txt','fileb.txt'
$soap.Envelope.Body.sampleObject | Add-Member -MemberType NoteProperty -Name fileNames -Value $fileNames
$soap.envelope.body.sampleObject | fl #1
write-host "`r`n" $soap.OuterXml #2
输出:
#1:对象包含文件名
fileNames : {filea.txt, fileb.txt}
Name : MySampleObject
#2:发送到xml Webservice时缺少文件名
<Envelope><Body><sampleObject><Name>MySampleObject</Name></sampleObject></Body></Envelope>
答案 0 :(得分:0)
请勿使用Add-Member
修改XML文档。
而是创建一个新节点,并使用sampleObject
方法将其附加到AppendChild()
:
$soap = [xml]@'
<Envelope>
<Body>
<sampleObject>
<Name>MySampleObject</Name>
</sampleObject>
</Body>
</Envelope>
'@
$filenames='filea.txt','fileb.txt'
foreach($filename in $filenames)
{
$NewNode = $soap.CreateElement('filenames')
$NewNode.InnerText = $filename
[void]$soap.Envelope.Body.sampleObject.AppendChild($NewNode)
}
XML文档现在包含您的filenames
个节点:
PS C:\> $soap.OuterXml
<Envelope><Body><sampleObject><Name>MySampleObject</Name><filenames>filea.txt</filenames><filenames>fileb.txt</filenames></sampleObject></Body></Envelope>