Reputation: 892
I have xml file like this
<?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>
I want to add an element in <Timestamp>
.
My Expectation like this
<?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>
Here's my attempt so far:
$fileName = "D:\file.xml"
$xmlDoc = [System.Xml.XmlDocument](Get-Content $fileName)
$newXmlEmployeeElement = $xmlDoc.CreateElement("Info")
$newXmlEmployee = $xmlDoc.DATA.Timestamp.AppendChild($newXmlEmployeeElement)
$xmlDoc.Save($fileName)
Anyone can help really appreciated. Thanks
Upvotes: 2
Views: 1355
Reputation: 11304
You can use the InnerText
property of the newly created element:
$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)
Getting the content of the file:
> 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>
Upvotes: 2
Reputation: 440162
The only thing missing from your code is to create the content for your new <Info>
element:
$newXmlEmployeeElement.InnerText = 'Started'
Upvotes: 3