2

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

1
  • You can't append to XML at the end. The XML specification defines a "Well-Formed" XML document to have only one element at the root (not an array). So adding to the end of a document makes the XML not "Well Formed". Many applications (like XML LOG files) do create arrays, but not all xml tools can use the array format. Commented Aug 23, 2019 at 9:28

2 Answers 2

3

The only thing missing from your code is to create the content for your new <Info> element:

$newXmlEmployeeElement.InnerText = 'Started'
Sign up to request clarification or add additional context in comments.

Comments

2

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.