gpt4 book ai didi

xml - Powershell:读取/编辑命名节点

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

我想从给定的XML文件中读取和编辑节点内容,然后将更改后的内容写回。
给定XML文件的内容:

<?xml version="1.0" encoding="UTF-8"?>
<SimBase.Document Type="ScenarioFile" version="4,5" id="Test">
<Descr>AceXML Document</Descr>
<Filename>Test.fxml</Filename>
<Flight.Sections>
...
<Section Name="DateTimeSeason">
<Property Name="Season" Value="Summer" />
<Property Name="Year" Value="2020" />
<Property Name="Day" Value="224" />
<Property Name="Hours" Value="12" />
<Property Name="Minutes" Value="2" />
<Property Name="Seconds" Value="17" />
</Section>
...
</Flight.Sections>
</SimBase.Document>
读取和写回XML文件的新副本可以很好地工作,但是我完全不知如何读取/编辑名为“DateTimeSeason”的节点的内容。它的节点,因为我不知道XPath。
我写的脚本内容:
Write-Host "Edit XML file"

# Load local functions
. .\LocalFunctions.ps1

# Working environment
$flightFileDir = 'E:\Temp\PowerShell\P3D\'
$flightFileNameIn = 'MauleLSZH.fxml'
$flightFileNameOut = 'MauleLSZHNew.fxml'
$flightFileIn = $flightFileDir + $flightFileNameIn
$flightFileOut = $flightFileDir + $flightFileNameOut

# Get correct date and time for flight file
$dateTimeArr = SetupDateTime
#$dateTimeArr # output content of resulting array

# Set up new XML object and read file content
$xmlFlight = New-Object System.XML.XMLDocument
$xmlFlight.Load($flightFileIn)

# Edit content of node named 'DateTimeSeason'
$data = $xmlFlight.'SimBase.Document'.'Flight.Sections'.Section[@name -eq 'DateTimeSeason'].Property[@name = 'Year']
$data # output for test purposes

# Output modified flight file
$xmlFlight.Save($flightFileOut)

Write-Host "New XML file created"
非常感谢您的帮助或提示
汉尼斯

最佳答案

你很亲密这是更正后的版本,它添加了新的“属性”并编辑了现有属性的“值”。

# Set up new XML object and read file content
$xmlFlight = New-Object System.XML.XMLDocument
$xmlFlight.Load($flightFileIn)

# Create new "Property" and append to the "DateTimeSeason" node
[System.Xml.XmlElement]$newElement = $xmlFlight.CreateElement('Property')
$newElement.SetAttribute('Name','NewName')
$newElement.SetAttribute('Value','NewValue')
$data = $xmlFlight.'SimBase.Document'.'Flight.Sections'.SelectSingleNode("//Section[@Name='DateTimeSeason']")
[void]$data.AppendChild($newElement)

# Edit "Year" Property on the "DateTimeSeason" node
$xmlFlight.'SimBase.Document'.'Flight.Sections'.SelectSingleNode("//Section[@Name='DateTimeSeason']").SelectSingleNode("//Property[@Name = 'Year']").Value = '2021'
# Could also use: $data.SelectSingleNode("//Property[@Name = 'Year']").Value = '2021'

$data.Property # output for test purposes

# Output modified flight file
$xmlFlight.Save($flightFileOut)

Write-Host "New XML file created"
注意:XPath区分大小写,因此“@name”在这里不起作用。必须使用“@Name”。

关于xml - Powershell:读取/编辑命名节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64295800/

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