我的文件.xml看起来像这样
<?xml version="1.0" encoding="UTF-8"?>
<layoutMaster xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="..\schema\m.xsd">
<deviceFamily>
<deviceFamilyUniqueID>DeviceFamilyWayside_2</deviceFamilyUniqueID>
<name>DeviceFamilyWayside_2</name>
<device>SAMSUNG</device>
<device>SONY</device>
<deviceFamilyOptions>
<name>false</name>
</deviceFamilyOptions>
</deviceFamily>
<deviceFamily>
<deviceFamilyUniqueID>DeviceFamilyWayside_4</deviceFamilyUniqueID>
<name>DeviceFamilyWayside_4</name>
<device>IPHONE</device>
<device>MAC</device>
<deviceFamilyOptions>
<name>false</name>
</deviceFamilyOptions>
</deviceFamily>
</layoutMaster>
我想在最后一个设备之后的
deviceFamily[deviceFamilyUniqueID ='DeviceFamilyWayside_2']
中添加一个新设备:因此,我在PowerShell中尝试了以下代码:
$Path = ".\config.xml"
[xml]$xmlFile = Get-Content -Path $Path
$xmlNewElementDevice = $xmlFile.CreateElement("device")
$xmlNewElementDevice.AppendChild($xmlFile.CreateTextNode("ALCATEL"))
$xmlTargetDeviceWayside = $xmlFile.SelectSingleNode('//layoutMaster/deviceFamily[deviceFamilyUniqueID = "DeviceFamilyWayside_2"]')
$xmlTargetDeviceWayside.InsertAfter($xmlNewElementDevice,$xmlTargetDeviceWayside.name)
但是我得到了这个错误:
Unable to convert the argument "1" (value "DeviceFamilyWayside_2") from "InsertAfter" to type "System.Xml.XmlNode":" Unable to convert "DeviceFamilyWayside_2" value from "System.String" to type "System.Xml.XmlNode". "
我想要得到的最终结果是这样的:
<?xml version="1.0" encoding="UTF-8"?>
<layoutMaster xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="..\schema\m.xsd">
<deviceFamily>
<deviceFamilyUniqueID>DeviceFamilyWayside_2</deviceFamilyUniqueID>
<name>DeviceFamilyWayside_2</name>
<device>SAMSUNG</device>
<device>SONY</device>
<device>ALCATEL</device> <--------------- here
<deviceFamilyOptions>
<name>false</name>
</deviceFamilyOptions>
</deviceFamily>
<deviceFamily>
<deviceFamilyUniqueID>DeviceFamilyWayside_4</deviceFamilyUniqueID>
<name>DeviceFamilyWayside_4</name>
<device>IPHONE</device>
<device>MAC</device>
<deviceFamilyOptions>
<name>false</name>
</deviceFamilyOptions>
</deviceFamily>
</layoutMaster>
最佳答案
在节点<deviceFamilyOptions>
之前插入新节点:
[xml]$xml = Get-Content -Path $Path
$newNode = $xml.CreateElement("device")
$newNode.InnerText = 'ALCATEL'
$parent = $xml.SelectSingleNode('//layoutMaster/deviceFamily[deviceFamilyUniqueID="DeviceFamilyWayside_2"]')
$ref = $parent.SelectSingleNode('./deviceFamilyOptions')
$parent.InsertBefore($newNode, $ref) | Out-Null
或者,选择最后一个
<device>
节点作为引用节点,之后再插入新节点:$parent = $xml.SelectSingleNode('//layoutMaster/deviceFamily[deviceFamilyUniqueID="DeviceFamilyWayside_2"]')
$ref = $parent.SelectSingleNode('./device[last()]')
$parent.InsertAfter($newNode, $ref) | Out-Null
关于xml - 如何使用insertAfter()在XML中的特定元素之后插入元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48602719/