【发布时间】:2020-06-10 20:57:32
【问题描述】:
这是我正在使用的 XML。这是在 sqlproj 文件中,并且希望将 ArtifactReference 的 Include 属性和节点元素 HintPath 中的值“..\cwdb.dacpac”更新为新值。
<ItemGroup>
<ArtifactReference Include="$(DacPacRootPath)\Extensions\Microsoft\SQLDB\Extensions\SqlServer\AzureV12\SqlSchemas\master.dacpac">
<HintPath>$(DacPacRootPath)\Extensions\Microsoft\SQLDB\Extensions\SqlServer\AzureV12\SqlSchemas\master.dacpac</HintPath>
<SuppressMissingDependenciesErrors>True</SuppressMissingDependenciesErrors>
<DatabaseVariableLiteralValue>master</DatabaseVariableLiteralValue>
</ArtifactReference>
<ArtifactReference Include="..\cwdb.dacpac">
<HintPath>..\cwdb.dacpac</HintPath>
<SuppressMissingDependenciesErrors>True</SuppressMissingDependenciesErrors>
<DatabaseVariableLiteralValue>cwdb</DatabaseVariableLiteralValue>
</ArtifactReference>
</ItemGroup>
以下部分代码基于此博客https://blogs.like10.com/2014/06/17/versioning-your-sql-server-database-using-team-build-and-release-management/,但它不会更新值。在对函数 Set-XMlElementsTextValue 的调用中,传递元素路径 HintPath 以更新其值。如何更改 Include 属性值?
function Get-XmlNode([ xml ]$XmlDocument, [string]$NodePath, [string]$NamespaceURI = “”, [string]$NodeSeparatorCharacter = ‘.’)
{
# If a Namespace URI was not given, use the Xml document’s default namespace.
if ([string]::IsNullOrEmpty($NamespaceURI))
{
$NamespaceURI = $XmlDocument.DocumentElement.NamespaceURI
}
# In order for SelectSingleNode() to actually work, we need to use the fully qualified node path along with an Xml Namespace Manager, so set them up.
$xmlNsManager = New-Object System.Xml.XmlNamespaceManager($XmlDocument.NameTable)
$xmlNsManager.AddNamespace(“ns”, $NamespaceURI)
$fullyQualifiedNodePath = “/ns:$($NodePath.Replace($($NodeSeparatorCharacter), ‘/ns:’))”
$node = $XmlDocument.SelectSingleNode($fullyQualifiedNodePath, $xmlNsManager)
return $node
}
function Set-XMlElementsTextValue([ xml ]$XmlDocument, [string]$ElementPath, [string]$TextValue)
{
$node = Get-XmlNode -XmlDocument $XmlDocument -NodePath $ElementPath
# If the node exists, update its value.
if ($node)
{
$node.InnerText = $TextValue
}
}
$path = "C:\Shared\DACPAC\"
$NewText = $path + "cwdb.dacpac"
$files = gci $env:BUILD_SOURCESDIRECTORY -recurse |
?{ $_.Extension -eq ".sqlproj" } |
foreach { gci -Path $_.FullName -Recurse -include *.sqlproj }
if($files)
{
foreach ($file in $files) {
[xml]$fileContent = Get-Content($file)
attrib $file -r
#Read in the file contents, update the element's value, and save the file.
Set-XMlElementsTextValue -XmlDocument $fileContent -ElementPath "Project.ItemGroup.ArtifactReference.HintPath" -TextValue $NewText
$fileContent.Save($file)
}
}
else
{
Write-Output "Found no *.sqlproj files."
}
【问题讨论】:
标签: xml powershell