I have xml file that contains version number. I know how to replace a string in a file but here I need to find something that start with 8 and replace it with a number. For an example
There are many places where the version 8.5.34.31.4 is displayed (There more many more and not all of them starts with <version...) I need to search something like 8 plus and replace it with another number like 8.5.34.31.5 For every xml the version is different (8.5.34, 8.6.22,...) So I thought to search the common beginning that is 8 Any idea how to do this?
CodePudding user response:
You can locate all nodes with string contents starting with 8.
by using the following XPath
expression:
//*[starts-with(text(), "8.")]
//*
describes "any node, at any place" in the document, [starts-with(text(), "8.")]
constrains the resulting set of nodes to only those where the embedded string content starts with "8."
.
To use it to locate specific xml nodes to replace, I'd suggest using the Select-Xml
cmdlet:
# define the new version number
$newVersion = '8.5.34.31.5'
# locate document on disk
$xmlFile = Get-Item .\path\to\document.xml
# use Select-Xml to read, parse, and query document for relevant nodes
$targetNodes = $xmlFile |Select-Xml -XPath '//*[starts-with(text(), "8.")]'
if($targetNodes){
$targetNodes |ForEach-Object {
# replace the string contents of the node with the new version number
$_.Node.InnerText = $newVersion
}
# save to disk after modifying
$targetNodes[0].Node.OwnerDocument.Save($xmlFile.FullName)
}