我想在我的自定义工具箱模块中创建一个函数,它使用自定义 xml 文件来提供说明(使用 $xmlpath
参数传递)。我如何验证提供的 xml 使用正确的 xml 类型/语法/格式(正确的元素、根节点等)?
如果我使用模式文件:如何使用 ex 验证 xml。测试 XML(PSCX cmdlet)?我是否在线存储 xsd 文件并在 xml 文档中指定它的路径?我是否将它存储在我的模块文件夹中并将其硬编码到脚本中?如果是这样,我如何指定架构路径?代码示例:
#Stored in ..\Modules\MyModule\Process-Config.psm1)
function Process-Config
{
param($xmlpath)
#Test that file is xml
try{ $xml = [xml](Get-Content $xmlpath) } catch {}
#Test that xml-file is valid against schema in Module-folder (Modules\MyModule\xmlschema.xsd)
#Using Test-XML PSCX cmdlet
Test-XML -Path $xmlpath -SchemaPath #Schemapath#
}
编辑:我发现 $PSScriptRoot
提供模块位置,因此我可以使用 $PSScriptRoot\Schemas\MySchema.xsd
作为路径。我认为它只适用于脚本,但似乎功能也适用。我是像这样在 xml 中为本地文件指定架构,还是在 xml 文件中使用架构地址在线发布 xsd?
最佳答案
如果您想要对 XML 文件进行基本测试(不验证 XML 模式或对外部模块的依赖性),您可以使用 function Test-XMLFile from Jonathan Medd :
function Test-XMLFile {
<#
.SYNOPSIS
Test the validity of an XML file
#>
[CmdletBinding()]
param (
[parameter(mandatory=$true)][ValidateNotNullorEmpty()][string]$xmlFilePath
)
# Check the file exists
if (!(Test-Path -Path $xmlFilePath)){
throw "$xmlFilePath is not valid. Please provide a valid path to the .xml fileh"
}
# Check for Load or Parse errors when loading the XML file
$xml = New-Object System.Xml.XmlDocument
try {
$xml.Load((Get-ChildItem -Path $xmlFilePath).FullName)
return $true
}
catch [System.Xml.XmlException] {
Write-Verbose "$xmlFilePath : $($_.toString())"
return $false
}
}
如果你想检查很多 XML 文件,你可以使用类似的东西
gci -recurse *.xml |% {
$outcome = Test-XMLFile $_.FullName -Verbose
}
它将告诉您哪个 XML 文件有什么问题。
关于xml - 如何验证 xml 的语法/格式是否正确(?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14423861/