-
Notifications
You must be signed in to change notification settings - Fork 64
/
Append-XmlElement.ps1
82 lines (50 loc) · 1.98 KB
/
Append-XmlElement.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
##############################################################################
# Script: Append-XmlElement.ps1
# Date: 4.Jun.2007
# Version: 1.0
# Author: Jason Fossen (www.WindowsPowerShellTraining.com)
# Purpose: Demo some XML manipulation.
# Legal: Script provided "AS IS" without warranties or guarantees of any
# kind. USE AT YOUR OWN RISK. Public domain, no rights reserved.
##############################################################################
function Append-XmlElement ($XmlDoc, $AppendToElement, $NewElementName, $Text = $null)
{
$element = $xmldoc.CreateElement($NewElementName)
if ($Text -ne $null) { $element.Set_InnerText($Text) }
$AppendToElement.AppendChild($element)
}
function Get-RawXML ($xmldoc)
{
$xmldoc.Save("$env:temp\tempxmlfile.xml")
get-content $env:temp\tempxmlfile.xml
remove-item $env:temp\tempxmlfile.xml -force
}
# Create a new blank XML document.
$xmldoc = new-object System.Xml.XmlDocument
# Create a top-level element and append to doc.
$Users = $xmldoc.CreateElement("Users")
$xmldoc.AppendChild($Users)
# Manually create and append a Person element.
$Person = $xmldoc.CreateElement("Person")
$fn = $xmldoc.CreateElement("FirstName")
$fn.Set_InnerText("Leslie")
$Person.AppendChild($fn)
$ln = $xmldoc.CreateElement("LastName")
$ln.Set_InnerText("Cummings")
$Person.AppendChild($ln)
$bd = $xmldoc.CreateElement("BirthDate")
$bd.Set_InnerText('18-May-1978')
$Person.AppendChild($bd)
$Users.AppendChild($Person)
# Now do the same, but use the function instead.
$newelement = append-xmlelement $xmldoc $xmldoc.Users "Person"
append-xmlelement $xmldoc $newelement "FirstName" "Matt"
append-xmlelement $xmldoc $newelement "LastName" "Shepard"
append-xmlelement $xmldoc $newelement "BirthDate" '22-Apr-1962'
# Show the XML text.
get-rawxml $xmldoc
# Remove just one element.
$element = $xmldoc.Users.Person[0]
$xmldoc.Users.RemoveChild($element)
# Remove all contents from the XML document.
# $xmldoc.RemoveAll()