Div*_*dev -1 regex xml windows batch-file
我有一个类型的XML文件
....
<sometag>
<tag attr_name1="long filename1" />
<tag attr_name2="long filename2" />
....
</sometag>
....
Run Code Online (Sandbox Code Playgroud)
在到目前为止,</sometag>我想添加<tag attr_name="long filename" />我的Windows批处理脚本中的代码之前:
@echo off
setlocal enableDelayedExpansion
set "newValue=^<tag attr_name="long filename" /^>
set newline=^& echo.
type "File.xml"|replace "(</tag>)" "!newValue!$1" >dupFile.xml
move /y "dupFile.xml" "File.xml"
Run Code Online (Sandbox Code Playgroud)
我得到“ Path not found - </tag>”,File.xml包含“未替换文件”。我知道从批处理文件编辑XML并不是最佳实践,但是不幸的是不能使用第三方可执行文件。有人可以帮我解决问题吗?
我还检查了有关使用批处理文件在XML中的标记之间更改数据的线程,当我在其中使用建议的代码并更改为我的要求时,遇到了以上错误。
如果</sometag>XML中仅出现一次,并且如果它不会破坏层次结构,则不会<tag>在之前的行中插入新节点,则可以通过循环遍历XML文件for /F,检查每一行是否包含</sometag>。找到后,只需<tag>在回显匹配的行之前先回显新的内容。
@echo off
setlocal
>"newfile.xml" (
for /f "usebackq delims=" %%I in ("xmlfile.xml") do (
set "line=%%I"
setlocal enabledelayedexpansion
if not "!line!"=="!line:/sometag=!" (
echo ^<tag attr_name="long filename" /^>
)
endlocal
echo(%%I
)
)
type "newfile.xml"
Run Code Online (Sandbox Code Playgroud)
但是实际上,假设您的XML完全有效,最优雅的解决方案是将XML解析为结构化数据,而不是复杂的文本以进行破解和抓取。这样,您的代码是被美化,缩小,丑化还是其他都无关紧要。无论缩进和换行,解析器仍然可以理解。您可以使用Windows中已内置的语言来执行此操作-VBScript,JScript,PowerShell,C#,然后列表继续。批处理可能是您所熟悉的唯一语言,但它不是Windows基本安装中可用的唯一语言。这是一个快速而肮脏的批处理+ PowerShell混合脚本来演示。(将其保存为.bat扩展名。)
<# : batch portion (within a multiline PowerShell comment)
@echo off & setlocal
set "infile=test.xml"
set "parentNode=sometag"
set "newTag=tag"
set "newAttr=attr_name"
set "attrVal=long filename"
set "outfile=new.xml"
powershell -noprofile -noninteractive "iex (${%~f0} | out-string)"
type "%outfile%"
goto :EOF
: end batch (multiline comment) / begin PowerShell hybrid code #>
[xml]$xml = gc $env:infile
$parent = $xml.documentElement.selectSingleNode("//$env:parentNode")
$new = $xml.createElement($env:newTag)
[void]$new.setAttribute($env:newAttr, $env:attrVal)
[void]$parent.appendChild($new)
$xml.save($env:outfile)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1887 次 |
| 最近记录: |