如何用PowerShell从USFX XML中提取指定章节的圣经经文
用PowerShell从USFX格式XML中提取指定经文
USFX采用扁平化XML结构:书籍、章节、经文仅作为空标签存在,实际经文内容拆分在后续的<w>标签中。以下是通过书籍简称、章节号、经文号提取对应内容的PowerShell实现方案:
实现脚本
# 配置目标经文参数 $bookAbbrev = "GEN" # 书籍简称(如GEN=创世记,需与USFX文件内标签一致) $targetChapter = 1 # 目标章节号 $targetVerse = 1 # 目标经文号 $usfxFilePath = "path/to/your/bible.usfx" # USFX文件路径 # 加载USFX XML文件 try { $usfxXml = [xml](Get-Content -Path $usfxFilePath -Encoding UTF8) } catch { Write-Error "加载XML文件失败:$_" exit 1 } # 定位目标书籍节点 $bookNode = $usfxXml.SelectSingleNode("//*[local-name()='$bookAbbrev']") if (-not $bookNode) { Write-Error "未找到指定书籍:$bookAbbrev" exit 1 } # 遍历节点收集目标经文内容 $inTargetChapter = $false $inTargetVerse = $false $verseContent = @() foreach ($childNode in $bookNode.ChildNodes) { # 进入目标章节 if ($childNode.LocalName -eq "chapter" -and $childNode.id -eq $targetChapter.ToString()) { $inTargetChapter = $true continue } # 离开当前章节(遇到新章节或其他书籍标签) if ($inTargetChapter -and ($childNode.LocalName -eq "chapter" -or $childNode.LocalName -match "^[A-Z]{2,}$")) { break } # 进入目标经文 if ($inTargetChapter -and $childNode.LocalName -eq "verse" -and $childNode.id -eq $targetVerse.ToString()) { $inTargetVerse = $true continue } # 离开当前经文(遇到新经文、章节或其他书籍标签) if ($inTargetVerse -and ($childNode.LocalName -eq "verse" -or $childNode.LocalName -eq "chapter" -or $childNode.LocalName -match "^[A-Z]{2,}$")) { break } # 收集<w>标签内的经文文本 if ($inTargetVerse -and $childNode.LocalName -eq "w") { $verseContent += $childNode.InnerText } } # 输出结果 if ($verseContent.Count -gt 0) { Write-Host "=== $bookAbbrev $targetChapter:$targetVerse ===" Write-Host ($verseContent -join ' ') } else { Write-Error "未找到指定经文:$bookAbbrev $targetChapter:$targetVerse" }
关键说明
- 结构适配:USFX无层级嵌套,通过遍历节点跟踪当前所处的章节/经文状态,确保只收集目标范围内的
<w>标签内容。 - 标签匹配:用
local-name()避免XML命名空间干扰,书籍标签匹配大写缩写(多数USFX版本采用3字母缩写)。 - 边界判断:通过检测新的章节、经文或书籍标签,精准终止内容收集,避免获取无关文本。
注意事项
- 替换
$usfxFilePath为实际的USFX文件路径,确保文件编码为UTF-8。 - 书籍简称需与USFX文件内的标签完全一致(可打开XML文件查看对应书籍的标签名)。
- 若USFX文件包含命名空间,需添加命名空间管理器调整XPath查询逻辑。
内容的提问来源于stack exchange,提问作者John Ranger
相关产品推荐
相关产品推荐

