PowerShell解压ZIP后提取XML标签属性值无输出问题求助
错误原因
- 路径定义使用全角中文引号,且分号错误写入路径字符串内部,导致XML文件路径无效
Select-Xml未指定读取的XML文件路径,且存在左括号缺失的语法错误- 需求是提取
<Report>标签的属性值,原代码错误取了节点InnerText内容 Set-Content未传入待写入的内容,所以输出文件为空
修复后代码
echo "unzipping file..." powershell -Command "Expand-Archive C:\path_to_zip_file -Destinationpath C:\path_to_to_destination_folder -Force; $Path = 'C:\path_to_to_destination_folder\file.xml'; $reportNode = (Select-Xml -Path $Path -XPath '//Report').Node; $outputStr = 'name {0} result_many fail, summary {1}, yes {2} , no {3}, finished {4}' -f $reportNode.name, $reportNode.summary, $reportNode.yes, $reportNode.no, $reportNode.finished; Set-Content -Path 'C:\path_to_to_destination_folder\result.txt' -Value $outputStr -Encoding UTF8" echo "done"
补充说明
- 替换代码中的占位路径为你实际的文件路径即可运行
- 如果XML有命名空间导致匹配不到
<Report>节点,把XPath改成'//*[local-name()="Report"]'即可跳过命名空间限制 - 代码中已经保留了固定前缀
result_many fail,如果该字段也需要从属性读取,自行修改拼接规则即可
内容的提问来源于stack exchange,提问作者konoha
相关产品推荐
相关产品推荐

