我有以下xml文件。我想在其中添加一些内容,我尝试了几种不同的方法,但似乎无法正确解决。
这就是xml文件的样子。
<Root>
<Device>
<Name>c:</Name>
<Time>
<TimeOfCheck>2014.3.18.22.36.43</TimeOfCheck>
<Size>120.14</Size>
<FreeSpace>38.18</FreeSpace>
</Time>
</Device>
<Device>
<Name>x:</Name>
<Time>
<TimeOfCheck>2014.3.18.22.36.43</TimeOfCheck>
<Size>23.23</Size>
<FreeSpace>11.47</FreeSpace>
</Time>
</Device>
</Root>
我正在尝试添加
<Time>
<TimeOfCheck>2014.3.18.22.36.43</TimeOfCheck>
<Size>120.14</Size>
<FreeSpace>25</FreeSpace>
</Time>
所以最终看起来像
<Root>
<Device>
<Name>c:</Name>
<Time>
<TimeOfCheck>2014.3.18.22.36.43</TimeOfCheck>
<Size>120.14</Size>
<FreeSpace>38.18</FreeSpace>
</Time>
<Time>
<TimeOfCheck>2014.3.18.22.36.43</TimeOfCheck>
<Size>120.14</Size>
<FreeSpace>25</FreeSpace>
</Time>
</Device>
<Device>
<Name>x:</Name>
<Time>
<TimeOfCheck>2014.3.18.22.36.43</TimeOfCheck>
<Size>23.23</Size>
<FreeSpace>11.47</FreeSpace>
</Time>
</Device>
</Root>
这是我加载xml文件的代码,用于检查是否存在名为C:或D的节点:
# Set the File Name
$filePath = "C:\dump\Report.xml"
# load the values that we going to add to the file
$disk = Get-WmiObject Win32_LogicalDisk -Filter "DriveType=3" | Select-Object DeviceID,@{Name="Size";Expression={"{0:N2}" -f($_.Size/1GB)}},@{Name="FreeSpace";Expression={ "{0:N2}" -f ($_.FreeSpace/1GB) }},@{Name="Time";Expression={Get-Date -format yyyy.M.d.H.mm.ss}}
# check if the file exists
If (Test-Path $filePath)
{#If the file exists
#load the file
[xml]$XmlExists = Get-Content $filePath
foreach($obj in $disk)
{$Node = "//Device/Name[text() ='" + $obj.DeviceID + "']"
$NodesTest =$XmlExists.SelectNodes("$node")
#check if the node exists
IF ($NodesTest.get_Count() -gt 0)
{
# The node exists but how do we add to it
}
Else
{
# The node does not exists how do we crate it
}
}
}
编辑1#
好的,已经成功使用此代码使其正常工作。
$AppendPath = "//Device[Name/text() ='" + $obj.DeviceID + "']"
# Build the xml to Append
$Time = $XmlExists.CreateElement('Time')
$TimeOfCheck = $XmlExists.CreateElement('TimeOfCheck')
$TimeOfCheck.set_InnerText($obj.time)
$Size = $XmlExists.CreateElement('Size')
$Size.set_InnerText($obj.Size)
$FreeSpace = $XmlExists.CreateElement('FreeSpace')
$FreeSpace.set_InnerText($obj.FreeSpace)
#Append opjects
$Time.AppendChild($TimeOfCheck)
$Time.AppendChild($Size)
$Time.AppendChild($FreeSpace)
$NodeToAppendTo= $XmlExists.SelectSingleNode($AppendPath)
$NodeToAppendTo.AppendChild($Time)
$XmlExists.Save($filePath)
要插入节点,XmlElement
类型上有很多方法(文档中每个元素一个实例)。
要将元素添加$ne
为被XmlElement
调用的最后一个子元素$xe
:
$xe.InsertAfter($ne, $xe.LastChild)
(如果$xe
没有子项,则将没有子项,$xe.LastChild
这意味着InsertAfter
在子项列表的开头插入,如果为空则可以。)
要创建新元素,您可以XmlDocument.CreateElement
。但是,如果您要创建的大部分内容不是动态确定的,请创建一个字符串并进行解析,然后从该文档中导入以插入到另一个文档中:
$tempDoc = [xml]"<element><inner>data</inner></element>";
$newEl = $tempDoc.DocumentElement;
$newEl = $destDoc.ImportNode($newEl, $true); # $true => deep
$destDoc.DocumentElement.InsertAfter($newEl, $destDoc.DocumentElement.LastChild);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句