查找和替换XML电话簿中的条目

时间:2018-09-11 15:59:46

标签: xml powershell xpath

我有以下XML电话簿,其电话号码以07和01开头,我想分别用+447和+441代替。有人可以建议一种简单的方法吗?

    <directory>
    <Entry>
      <Name>***Travis</Name>
      <extension>02089425943</extension>
   </Entry>

   <Entry>
      <Name>***Nina</Name>
      <extension>0177377106</extension>
   </Entry>

   <Entry>
  <Name>***Yusra</Name>
  <extension>07790400192</extension>
   </Entry>

   <Entry>
     <Name>***Raoul</Name>
     <extension>07818838683</extension>
    </Entry>
 </directory> <directory>

任何帮助都感激不尽..

2 个答案:

答案 0 :(得分:0)

您可以将其视为纯文本替换:

const
    path = require('path'),
    webpack = require('webpack'),
    MiniCssExtractPlugin = require('mini-css-extract-plugin');

const srcFolder = path.resolve(__dirname, 'src');

const miniCssExtractPlugin = new MiniCssExtractPlugin();

const config = {
    resolve: {
        modules: [ srcFolder, 'node_modules', ],
        extensions: [ '.js', ],
    },

    entry: [
       path.resolve(srcFolder, 'styles.scss'),
    ],

    output: {
        path: path.resolve(__dirname, 'build'),
    },

    module: {

        rules: [
            {
                test: /\.(sa|sc|c)ss$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    'css-loader',
                    'sass-loader'
                ],
            }

        ]
    },
    plugins: [
        miniCssExtractPlugin
    ]
};

module.exports = config;

(Get-Content 'C:\folder\phonebook.xml') ` -replace '<extension>01','<extension>+441' ` -replace '<extension>07','<extension>+447' | Set-Content 'C:\folder\phonebook.xml' 括在方括号中,以便powershell读取它,然后释放文件锁,而没有这些,使用Get-Content时会出错。

我正在使用反引号将命令放在多行中,这只比单行代码更具可读性:

Set-Content

答案 1 :(得分:0)

您还可以使用PowerShell的本机XML支持。

$xml = [xml] (Get-Content ".\directory.xml")
foreach($entry in $xml.directory.Entry)
{
    if ($entry.extension.StartsWith("07"))
    {
        $entry.extension = "+447" + $entry.extension.Substring(2)
    }
    if ($entry.extension.StartsWith("01"))
    {
        $entry.extension = "+441" + $entry.extension.Substring(2)
    }
}
$xml.directory.Entry
$xml.Save(".\directory.xml")

# Name      extension    
# ----      ---------    
# ***Travis 02089425943  
# ***Nina   +44177377106 
# ***Yusra  +447790400192
# ***Raoul  +447818838683