【问题标题】:Powershell split xml node and add in same filePowershell拆分xml节点并添加到同一个文件中
【发布时间】:2016-05-27 18:12:51
【问题描述】:

我正在解析 xml 文件,特别是节点,我必须先对其进行拆分,然后在其中执行添加操作,然后在其上方插入新节点。

我的 XML 文件:

<Project Default="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="1.0">
<Items>
    <Resource Include="File\Scripts\Main.xml" />
    <Resource Include="File\Scripts\File101_102.xml" />
</Items>
</project>

Powershell:

[xml]$xdoc = Get-Content $path
$NodeInsertAfter=$xdoc.project.Items.Resource[0]
$StringtoSplit=$xdoc.project.Items.Resource[1]
$a=$StringtoSplit.Include.ToString().split('\')
$a=$StringtoSplit.Include.ToString().split('\')
$a

我已经到达读取节点但是我将如何使用 split 函数来增加文件编号,即 File102_103.xml

我的输出必须是:

<Project Default="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="1.0">
<Items>
    <Resource Include="File\Scripts\Main.xml" />
    <Resource Include="File\Scripts\File102_103.xml" />
    <Resource Include="File\Scripts\File101_102.xml" />
</Items>

【问题讨论】:

    标签: xml powershell


    【解决方案1】:

    您可以使用regex 来提取这两个数字:

    $fileNumberRegex = '(\d+)_(\d+)'
    $match = [regex]::Match($StringtoSplit.Include, $fileNumberRegex)
    $StringtoSplit.Include -replace $fileNumberRegex, ('{0}_{1}' -f (1+$match.Groups[1].Value), (1+$match.Groups[2].Value))
    

    【讨论】:

    • 只需使用Clone() 克隆$NodeInsertAfter 节点,然后使用我上面的脚本更改文件名,最后使用AppendChild 函数附加节点。
    猜你喜欢
    • 2014-12-22
    • 1970-01-01
    • 1970-01-01
    • 2021-04-22
    • 2016-02-09
    • 2015-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多