Powershell方法1)确定XML值是否存在,以及2)替换值


<?xml version="1.0" encoding="utf-8"?>
<Test1>
<Test1Properties>
<Property1>replace this</Property1>
</Test1Properties>
<Test1Sources>
<Source1>
<SourceReference>sourceref</SourceReference>
<SourceType>None</SourceType>
</Source1>
<Source2>
<Source2Properties>
<Provider>prov</Provider>
<ProviderKey>some-guid</ProviderKey>
</Source2Properties>
</Source2>
</Test1Sources>
</Test1>

根据上面的xml,我需要在Powershell中完成3个任务:

  1. 替换新值
  2. 验证value =无
  3. 如何确定是否Source2>

我假设读取xml变量是最好的开始方式?如:

[xml]$xmlAttr = Get-Content -Path TestFile.xml

我几乎不使用Powershell,更不用说XML了,所以希望这些是相当简单的问题。提前谢谢。

下面是一些如何处理XML数据的示例:

# Deserialize the XML text Option 1.
# This is syntactically simpler but is susceptible to encoding issues.
[xml]$xml = Get-Content -Path TestFile.xml
# Deserialize the XML text Option 2. Must use full path in Load method.
$xml = [xml]::new()
$xml.Load('C:TempTestFile.xml')
# Update Node Property1 value
$xml.Test1.Test1Properties.Property1 = 'new value'
# Return True if SourceType node has value of None
$xml.Test1.Test1Sources.Source1.SourceType -ceq 'None'
# Return True if Source2Properties Exists as a child node of Source2
$xml.SelectSingleNode("//Test1/Test1Sources/Source2/Source2Properties") -is [System.Xml.XmlElement]
# Save results in your xml file. Must use a full path in Save() method.
$xml.Save('C:tempTestFile.xml')

相关内容

最新更新