作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
给定以下示例脚本(在我的硬盘上保存为 sample.txt ):
DECLARE @xVar XML
SET @xVar =
'<bookstore>
<book>
<title>Writing Secure Code</title>
<author>
<first-name>Michael</first-name>
<last-name>Howard</last-name>
</author>
<author>
<first-name>David</first-name>
<last-name>LeBlanc</last-name>
</author>
<price>39.99</price>
</book>
<book>
<title>Old Man and the sea</title>
<author>
<first-name>Earnest</first-name>
<last-name>Hemmingway</last-name>
</author>
<price> 9.99</price>
</book>
</bookstore>
'
SELECT nref.value('first-name[1]', 'nvarchar(50)') FirstName,
nref.value('last-name[1]', 'nvarchar(50)') LastName
FROM @xVar.nodes('//author') AS R(nref)
WHERE nref.exist('.[first-name != "David"]') = 1
Set-StrictMode -Version Latest
cls
#The list of fields that I want to find
[array]$expected_fields = "title", "price"
#extract the xml from sample.txt and put it in an xml variable
[string]$file_script = Get-Content "C:\PowerShellScripts\sample.txt"
[int]$start_pos = $file_script.IndexOf("'") + 1
[int]$end_pos = $file_script.SubString($start_pos + 1).IndexOf("'") + 1
[xml]$xml_result = $file_script.SubString($start_pos,$end_pos)
#NOTE: THIS IS THE PART THAT FEELS WRONG
#Convert the xml snipput into CSV file and then get the headers (which is the only thing I want)
$export_file_name = "C:\PowerShellScripts\test.csv"
Select-Xml 'child::bookstore/book' $xml_result | Select-Object -expand Node | Export-Csv $export_file_name -NoTypeInformation -Delimiter:"`t" -Encoding:UTF8
[string]$field_names = Get-Content $export_file_name | Select-Object -first 1
Remove-Item "C:\Users\Jennifer\Google Drive\PowerShellScripts\test.csv"
[array]$found_fields = $field_names.Replace("""","").Split("`t")
#report new fields
foreach ($specific_field in $found_fields) {
if ($expected_fields -notcontains $specific_field)
{
Write-Host "New field found:" $specific_field
}
}
最佳答案
尝试更改您的 -Expand
来自 节点 至 姓名 (和 Where-Object
排除标题和价格)
$xml_result.SelectNodes("bookstore/book/*") | Select-Object -Expand Name | Where-Object { ($_ -ne "title") -and ($_ -ne "price") }
book
的任何意外子节点.
关于powershell - 如何从 XML 获取子节点列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11074341/
我是一名优秀的程序员,十分优秀!