【问题标题】:Use Format-Table to format XML node with attribute使用 Format-Table 格式化带有属性的 XML 节点
【发布时间】:2015-07-18 04:01:45
【问题描述】:

Powershell: How to use Format-Table with XML data 详细说明了如何处理带有属性的 XML 元素。我的情况与此不同。

在大多数情况下,不存在任何属性:

<content type="application/xml">
  <m:properties>
    <d:Title>Vivamus fermentum semper porta</d:Title>

可以用这段代码处理:

...
$properties = $xml.feed.entry.content.properties
$properties | Format-Table -Property @{Label="Title"; Expression={$_.Title}}
...

甚至:

$properties | Format-Table -Property Title

然而,在少数情况下,xml:space 属性存在:

<content type="application/xml">
  <m:properties>
    <d:Title xml:space="preserve">Lorem ipsum dolor sit amet </d:Title>

需要此代码:

...
$properties = $xml.feed.entry.content.properties
$properties | Format-Table -Property @{Label="Title"; Expression={$_.Title."#text"}}
...

有没有 DRYer 方法来处理这种情况?

【问题讨论】:

  • 我想我有一个想法,但您能否包含一个样本,该样本具有您所指的两种差异进行测试。由于您的第二个 sn-p 看起来 非常 与第一个相似。
  • 我更新了我的问题,@Matt。

标签: xml powershell powershell-3.0


【解决方案1】:

我最初试图想出一些更复杂的东西,但如果这符合你的需要,我就不需要拔头发了。我做了一个函数来检查传递的对象。如果该对象包含“#text”属性,那么我们将其返回。否则只返回传递的对象。

function Get-XMLElementStringData{
    param(
        # In testing could be a string or System.Xml.XmlElement so I do not type this
        $Element
    )

    # Check for the existence of the property. There are other methods but the result is the same. 
    # If($Element."#text"){$Element."#text"} would also work.
    If($Element.PsObject.Properties.Name -contains "#text"){
        $Element."#text"
    } Else {
        $Element
    }
}

这样我就可以像这样更改您的输出代码:

$properties | Format-Table @{Label="Title"; Expression={Get-XMLElementStringData $_.Title}}

如果您正在寻找一种 DRYer 方法,那么也许我们可以研究另一种方法。

【讨论】:

    猜你喜欢
    • 2022-01-01
    • 1970-01-01
    • 2022-11-19
    • 1970-01-01
    • 2021-05-18
    • 1970-01-01
    • 1970-01-01
    • 2010-12-28
    • 1970-01-01
    相关资源
    最近更新 更多