我在PowerShell中,操作xml文档(.NET的System.Xml.XmlDocument类)。 我想在 xml 属性之间添加自定义空格。 我在 .NET 中找不到它的 API 调用,而且在线似乎没有人试图这样做。 这是我正在尝试做的事情的简化示例,但有一个我不知道该怎么称呼的评论:
$xmlDoc = [xml]@"
<root>
<test Id="1" a="a" b="b" />
<test Id="2" a="a" b="b" />
</root>
"@
$elements = @($xmlDoc.SelectNodes('//*'))
foreach($element in $elements)
{
$attributes = $element.Attributes
foreach($attribute in $attributes)
{
#
# How do I access the whitespace around the attributes?
#
}
}
# Output to screen exactly what will be saved to disk
$tempFile = [System.IO.FileInfo]([System.IO.Path]::GetTempFileName())
$xmlDoc.save($tempFile)
foreach($line in (Get-Content $tempFile))
{ Write-Host $line }
Remove-Item $tempFile
有谁知道如何访问System.Xml.XmlAttribute周围的空格?
不幸的是,没有办法使用 XmlDocument(和相关)或 XDocument(和相关)来做到这一点。即使是像 XmlTextWriter 这样的低级东西也不允许你在属性之间添加额外的空格或新行。
每个 XmlNode/XObject 都可以序列化,因此您可以编写自己的特殊格式序列化或在标准序列化过程之后对生成的 XML 进行后处理。希望这有帮助