如何使用PowerShell在XML中添加新属性?

cbeh67ev  于 2023-05-17  发布在  Shell
关注(0)|答案(2)|浏览(128)

我有这样的xml文件

<?xml version="1.0" encoding="UTF-8"?>
<DATA>
  <Platform>
    <D1>8536</D1>
  </Platform>
  <Timestamp>
    <Create>Friday, August 23, 2019 4:34:18 PM</Create>
  </Timestamp>
</DATA>

我想在<Timestamp>中添加一个元素。我的期望是这样的

<?xml version="1.0" encoding="UTF-8"?>
<DATA>
  <Platform>
    <D1>8536</D1>
  </Platform>
  <Timestamp>
    <Create>Friday, August 23, 2019 4:34:18 PM</Create>
    <Info>Started</Info>
  </Timestamp>
</DATA>

以下是我目前的尝试:

$fileName = "D:\file.xml"
$xmlDoc = [System.Xml.XmlDocument](Get-Content $fileName)
$newXmlEmployeeElement = $xmlDoc.CreateElement("Info")
$newXmlEmployee = $xmlDoc.DATA.Timestamp.AppendChild($newXmlEmployeeElement)
$xmlDoc.Save($fileName)

任何人都可以帮助真的很感激。谢谢

2exbekwf

2exbekwf1#

代码中唯一缺少的是为新的<Info>元素创建内容:

$newXmlEmployeeElement.InnerText = 'Started'
enyaitl3

enyaitl32#

您可以使用新创建的元素的InnerText属性:

$fileName = "test.xml"
$xmlDoc = [System.Xml.XmlDocument](Get-Content $fileName)
$newXmlEmployeeElement = $xmlDoc.CreateElement("Info")
$newXmlEmployee = $xmlDoc.DATA.Timestamp.AppendChild($newXmlEmployeeElement)

# Set the value via this line!
$newXmlEmployeeElement.InnerText = "1.2.3.4"

$xmlDoc.Save($fileName)

获取文件的内容:

> gc .\test.xml
<?xml version="1.0" encoding="UTF-8"?>
<DATA>
  <Platform>
    <D1>8536</D1>
  </Platform>
  <Timestamp>
    <Create>Friday, August 23, 2019 4:34:18 PM</Create>
    <Info>1.2.3.4</Info>
  </Timestamp>
</DATA>

相关问题