嗨,我有一个XML文件,如
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<ExternalLibPath>XYZ</ExternalLibPath>
<PropertyModelSDKPath>ABC</PropertyModelSDKPath>
</PropertyGroup>
<PropertyGroup Condition="xyz" == 'true'">
<DiagnosticConditionalDefines>FeatureA</DiagnosticConditionalDefines>
</PropertyGroup>
</Project>
我希望使用powershell将值设置为FeatureB。
我可以做这样的事情来获得价值
$xmlFile = [XML] (get-Content filename)
$xmlFile.Project.PropertyGroup.DiagnosticConditionalDefines
但是要写它,我需要做一些类似的事情
$xmlFile.Project.PropertyGroup[2].DiagnosticConditionalDefines="FeatureB"
我不愿意在这里给索引值"2“来写到这个节点,因为它可能不会保持这种状态。
如何在不添加索引的情况下编辑值?
发布于 2015-02-13 10:52:57
我就是这么做的
$xmlFile = [xml] (Get-Content $file)
$value=[string] $xmlFile.Project.PropertyGroup.DiagnosticConditionalDefines
for( $i=0; $i -lt $xmlFile.Project.PropertyGroup.Count ; $i++)
{
if($xmlFile.Project.PropertyGroup[$i].DiagnosticConditionalDefines.Length -gt 0)
{
$xmlFile.Project.PropertyGroup[$i].DiagnosticConditionalDefines
$xmlFile.Project.PropertyGroup[$i].DiagnosticConditionalDefines += "TEST"
}
}
$xmlFile.Save($file.FullName)
发布于 2015-02-12 08:59:42
我尝试了下面的代码,它为我工作。代码可能不是优化的,我是powershell的初学者。
$xml = [xml](get-content "C:\temp.xml")
foreach($item in $xml.Project.PropertyGroup)
{
if($item.Condition -eq "'xyz' == 'true'")
{
$item.DiagnosticConditionalDefines = "FeatureDB"
}
}
$xml.Save($ProvisionFilePath)
发布于 2015-02-13 10:36:48
有了对XML的更正,以下是基于属性修改元素的几种PowerShell-y方法之一:
$xml = [xml](Get-Content $fileName)
$node = $xml.Project.PropertyGroup |
Where { $_.GetAttribute('Condition') -eq "'xyz' == 'true'"}
$node.DiagnosticConditionalDefines = 'new value'
您可以通过再次执行选择来确认它修改了原始的XML结构,这一次没有将它分配给一个变量:
$xml.Project.PropertyGroup | ? { $_.GetAttribute('Condition') -eq "'xyz' == 'true'"}
第二种验证方法是将更新的内容写回文件,然后检查文件:
$xml.Save($fileName)
https://stackoverflow.com/questions/28482305
复制相似问题