-3

I was wondering how to edit a specific attribute in an XML file.

the attribute that I would like to edit looks like this:
<Data key="serial">912487015087068085841514</Data>
I would like the file to set the value to a random 24 digit number.

  • First you gotta find a command line tool capable of editing XML and invoke it. You don't edit files using batch scripts, you invoke commands to programs that can. – Jeff Mercado Jul 04 '16 at 00:22
  • okay. I wasnt sure because you can edit .TXT files using batch – Nathan Anderson Jul 04 '16 at 00:24
  • 1
    You _can_, but it's incredibly difficult. Of course, that doesn't stop this question from getting asked here [all](http://stackoverflow.com/questions/1946717/edit-xml-with-batch-file) [the](http://stackoverflow.com/questions/24584289/editing-xml-with-bat) [time](http://stackoverflow.com/questions/5298293/batch-file-code-to-edit-a-string-between-strings-in-a-dtsconfig-xml-file). – SomethingDark Jul 04 '16 at 01:00

1 Answers1

0

PowerShell is pretty good at handling XML data. I'm posting this to avert suggestions to use sed, jrepl.bat, or other text-manipulation tools. XML should be handled as a hierarchical object.

<# : batch portion
@echo off & setlocal

set "xmlfile=test.xml"

powershell -noprofile "iex (${%~f0} | out-string)"

goto :EOF
: end batch / begin PowerShell hybrid code #>

function rnd([int]$digits) {
    $x = foreach ($i in 1..$digits) { get-random -min 0 -max 9 }
    $x -join ''
}

[xml]$xml = gc $env:xmlfile
$xml.SelectSingleNode('//Data[@key="serial"]/text()').data = rnd 24
$xml.Save($env:xmlfile)

If you'd like, you can change the rnd() function to generate 24 hexadecimal characters (0-9 and a-f) for even more randomness.

function rnd([int]$digits) {
    $x = foreach ($i in 1..$digits) { (get-random -min 0 -max 16).toString('x') }
    $x -join ''
}

... Or you can generate from every alphanumeric character for even more.

function rnd([int]$digits) {
    $x = foreach ($i in 1..$digits) { [char](48..57 + 65..90 + 97..122 | get-random) }
    $x -join ''
}

But the rnd() function is somewhat re-inventing the wheel. You can generate plenty of randomness by using .NET's GUID class.

$xml.SelectSingleNode('//Data[@key="serial"]/text()').data = [guid]::NewGuid()
rojo
  • 24,000
  • 5
  • 55
  • 101