gpt4 book ai didi

xml - 如何在PowerShell中自动创建XML的新元素?

转载 作者:行者123 更新时间:2023-12-03 00:32:16 25 4
gpt4 key购买 nike

我有一个包含此内容的文本文件:

123asdf
abdfeef
22343sf
dfafdsf

该文件的内容正在更改。

我想创建一个xml文件,其中一个元素包含文本文件内容。

我试过了,但是所有内容都在同一个元素中:
$Getfile = Get-Content .\DeleteFile.txt
$TimeStamp = [System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId(
(Get-Date), 'Taipei Standard Time')
$delete_file = @"
<?xml version="1.0" encoding="UTF-8"?>
<Handling>
<Deleted>
<1>$Getfile</1>
</Deleted>
<TimeStamp>$TimeStamp</TimeStamp>
</Handling>
"@
$delete_file | Out-File .\DeleteFile.xml

输出:
<?xml version="1.0" encoding="UTF-8"?>
<Handling>
<Deleted>
<1>123asdf abdfeef 22343sf dfafdsf</1>
</Deleted>
<TimeStamp>12/04/2019 17:49:06</TimeStamp>
</Handling>

我的期望是输出将是这样的:
<?xml version="1.0" encoding="UTF-8"?>
<Handling>
<Deleted>
<1>123asdf</1>
<2>abdfeef</2>
<3>22343sf</3>
<4>dfafdsf</4>
</Deleted>
<TimeStamp>12/04/2019 17:49:06</TimeStamp>
</Handling>

谁能帮我吗?

最佳答案

内容进入同一元素,因为您没有创建新的XML元素。要添加元素,请创建一个XML对象并使用其CreateElementAppendChild方法。像这样

# Skeleton document that is filled later
[xml]$d = @'
<Handling>
<Deleted />
<TimeStamp />
</Handling>
'@

# Dummy data, read these from a file instead
$data = @('123asdf', 'abdfeef', '22343sf', 'dfafdsf')

# XPath selects the node under which new elements are added
$n = $d.SelectSingleNode('/Handling/Deleted')

# Loop through input data
for($i=0; $i -lt $data.length; ++$i) {
# Create new element, Element name is from loop counter
$e = $d.CreateElement(($i+1).ToString())
$e.InnerText = $data[$i]
# Add the new node into document
$n.AppendChild($e) | out-null
}
# Display the results.
$d.save([console]::out)

输出:
<?xml version="1.0" encoding="ibm850"?>
<Handling>
<Deleted>
<1>123asdf</1>
<2>abdfeef</2>
<3>22343sf</3>
<4>dfafdsf</4>
</Deleted>
<TimeStamp />
</Handling>

关于xml - 如何在PowerShell中自动创建XML的新元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59173230/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com