Powershell 从 XML 文件中提取字符串

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

尝试从文件中提取一些字符串。以下是文件中文本的简化示例:

<modelName>thing1</modelName><gtin>123456789</gtin><description>blah blah blah</description>
<modelName>thing2</modelName><gtin>789456123</gtin><description>blah blah blah</description>
<modelName>thing3</modelName><gtin>456789123</gtin><description>blah blah blah</description>

我想提取每行的这一部分:

<gtin>xxxxxxx</gtin>
并将它们放入另一个文件中。

我不想要整条线,只想要GTIN。

这是我尝试过的:

Get-Content -Path C:\firstFile.xml -Readcount 1000 | foreach { $_ -match "<gtin1>*</gtin1>" } | out-file C:\gtins.txt

但是你可能猜到它不起作用。

非常感谢任何帮助。我有一种感觉,这太容易了。

谢谢!

xml powershell
2个回答
2
投票

编辑: Ansgar Wiechers 是对的,您不应该使用正则表达式来解析 XML,并且正确的 XML 解析是最好的选择。)

您可以使用

Select-String
和正则表达式提取子字符串。示例:

Get-Content "C:\firstfile.xml" | Select-String '(<gtin>.+</gtin>)' | ForEach-Object {
  $_.Matches[0].Groups[1].Value
}

如果您只需要标签之间的值,请移动

(
)
以仅包围表达式的
.+
部分。

有关正则表达式的更多信息:

PS C:\> help about_Regular_Expressions

0
投票

不要使用正则表达式解析 XML。

使用实际的 XML 解析器从 XML 文件中提取数据。

[xml]$xml = Get-Content 'C:\firstfile.xml'
$xml.SelectNodes('//gtin') | Select-Object -Expand '#text'
© www.soinside.com 2019 - 2024. All rights reserved.