繁体   English   中英

通过bat文件更改XML属性

[英]Change XML Attribute By bat file

我有以下XML文件:

<MyXML myatt="true">
   <MyElement>Test</MyElement>
</MyXML>

我想通过.bat文件更改attirbute myatt
我该如何使用PowerShell?
谢谢!

我想我找到了解决方案,但我不认为这是最好的解决方案

<# : batch portion
@echo off
setlocal

set "xmlfile=test.xml"

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

: end batch / begin PowerShell #>

[xml]$xml = gc $env:xmlfile
$nodes = $xml.SelectNodes('MyXML')
foreach($node in $nodes)
{
     node.SetAttribute('myatt','false')
}
$xml.Save($env:xmlfile)
@ECHO Off
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET "destdir=U:\destdir"
SET "filename1=%sourcedir%\q35534146.txt"
SET "outfile=%destdir%\outfile.txt"

SET "tag=%1"
SET "attribute=%2"
SET "value=%~3"
IF NOT DEFINED value ECHO(Required tag, attribute, "value"&GOTO :EOF 

(
FOR /f "usebackqdelims=" %%a IN ("%filename1%") DO (
 FOR /f "tokens=1,2delims=<=> " %%c IN ("%%a") DO (
  SET "changed="
  IF /i "%%c"=="%tag%" IF "%%d"=="%attribute%" SET "changed=y"&ECHO(^<%%c %attribute%="%value%"^>
  IF NOT DEFINED changed ECHO(%%a
 )
)
)>"%outfile%"

GOTO :EOF

您需要更改sourcedirdestdir的设置以适合您的情况。

我使用了一个名为q35534146.txt的文件, q35534146.txt包含用于测试的数据。

产生定义为%outfile%的文件

我使用的文件名是.txt ,并根据需要替换为.xml并不重要。

请注意,这仅替换任何以行开头

定界符标记定界符属性定界符任何

<tag attribute="value">

运行为

thisbatch标签属性“需要值”

仅在值包含空格之类的分隔符时才需要使用引号。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM