在 Perl 中格式化 xml 文件很困难

问题描述 投票:0回答:1

我并不是真正的 Perl 开发人员,但我必须解析/修改几个文件,因此认为 Perl 将是这个临时脚本的不错选择......所以我提前道歉,我可能错过了一个重要的基本概念(我实际上让 ChatGPT 为我生成了初始脚本)。

由于某种原因,我的脚本无法使用

xmllint
或看似任何其他库或 CLI 可执行文件来简洁地(不指定 XML 的架构)格式化我的 XML 文件...我想知道这是否有什么与 IPC 和输出/输入数据管道有关(在 TypeScript、C# 等中我不担心的概念)?

这是我尝试的一些代码:

#!/usr/bin/perl

use strict;
use warnings;

# Check if the command-line argument is provided
if (@ARGV != 1) {
    die "Usage: $0 <csproj_file>\n";
}

my $csproj_file = $ARGV[0];

# Format the entire XML file using xmllint
open my $xmllint_pipe, '|-', 'xmllint --format --recover - ' or die "Cannot open pipe to xmllint: $!";
print $xmllint_pipe $content;  # Send the original XML content to xmllint for formatting
close $xmllint_pipe;  # Close the pipe

# Write the updated and formatted content back to the file
open my $output_fh, '>encoding(utf8)', $csproj_file or die "Could not open file '$csproj_file' for writing: $!";
print $output_fh $content;  # Write the formatted content to the file
close $output_fh;  # Close the filehandle

my $formatted_content = `xmllint --format $csproj_file`;

# Write the updated and formatted content back to the file
open my $output_fh, '>encoding(utf8)', $csproj_file or die "Could not open file '$csproj_file' for writing: $!";
print $output_fh $content;  # Write the formatted content to the file
close $output_fh;  # Close the filehandle

基本用例:我只想修复我通过脚本编辑的一些 XML 文件中的间距/制表符(这不是特别重要,但我想如果很简单的话我也可以)。

perl io ipc
1个回答
0
投票

所以我接受了 @Gilles Quénot 的提示,并在我的平台上使用了底层 shell 脚本语言(即 cmd 或 PowerShell,因为我目前在 Windows 上)。

只是寻求 XML 格式的简单解决方案。不是最有效的,但很容易阅读。以下是我为使其正常工作所做的相关修改:

my $tmp_filepath = $csproj_file . '_tmp';

print "xmllint --format $csproj_file > $tmp_filepath";

system("xmllint --format $csproj_file > $tmp_filepath");

print "move $tmp_filepath $csproj_file";

system("move $tmp_filepath $csproj_file");

基本上:只需使用临时文件,并运行基本的 CMD 命令即可:首先,格式化 XML 并保存在临时文件中;其次,将临时文件名重命名为原始文件名。

© www.soinside.com 2019 - 2024. All rights reserved.