Powershell: add child node in XML

后端 未结 1 589
不思量自难忘°
不思量自难忘° 2021-01-24 00:29

I have the following XML tree:


  
    
    
          


        
相关标签:
1条回答
  • 2021-01-24 01:06

    You have to iterate over each node and create the address node for each of them:

    $fileName = "C:\code\employees.xml";
    $xmlDoc = [System.Xml.XmlDocument](Get-Content $fileName); 
    $xmlDoc.company.employees.employee | Foreach-Object {
            $_.AppendChild($xmlDoc.CreateElement("address"))
        }
    $xmlDoc.Save($fileName);
    

    Output:

    <company>
      <employees>
        <employee name="Dwight" id="e1000" department="sales">
          <address />
        </employee>
        <employee name="Toby" id="e1001" department="hr">
          <address />
        </employee>
        <employee name="Jim" id="e1002" department="sales">
          <address />
        </employee>
        <employee name="Pam" id="e1003" department="reception">
          <address />
        </employee>
      </employees>
    </company>
    

    If you need more subchildren, just assign the output of the AppendChild to a variable and use it to Append them.

    0 讨论(0)
提交回复
热议问题