根据属性值获取元素

时间:2016-08-05 09:52:46

标签: xml powershell

我有一个XML文档,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<mailmanager xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <locations>
<store id="57fb3dc3-8716-4a71-ab5c-d8c76e20640b">
  <type>msg</type>
  <description>01038 - Wood Wharf - Fire</description>    <folder>SharePoint:https://site.domain.com/legal/01038/documents/Forms/CRMView.aspx</folder>
</store>
<store id="6873a00e-e49c-4602-af27-49d2900563d3">
  <type>msg</type>
  <description>01038 - Wood Wharf - Fire</description>
  <folder>\\site.domain.com\legal\01038\documents\</folder>
  <fileable>0</fileable>
</store>
<store id="d5e3af58-bc1d-4e45-a2dc-a9ceed803456">
  <type>msg</type>
  <description>05515 - IRELAND - Dart Underground   -  DART UNDERGROUND INTERCONNECTOR PROJECT</description>     <folder>SharePoint:https://site.domain.com/legal/05515/documents/Forms/CRMView.aspx</folder>
</store>

有数千个store元素。

使用PowerShell,是否可以根据folder值获取整个父元素(即包含所有内容的商店)?因此,如果folder值包含site.domain.com/legal/02323,我会获得父元素。

3 个答案:

答案 0 :(得分:1)

是的,使用带有contains() function的XPath表达式:

$Search = "site.domain.com/legal/01038"
$XmlDoc = [xml](Get-Content .\mydocument.xml)
$StoreNode = $xmlDoc.SelectSingleNode("//store[folder[contains(.,'$search')]]")

您也可以使用Select-Xml cmdlet

执行上述操作
$Search = "site.domain.com/legal/01038"
$StoreNode = Select-Xml -Path .\mydocument.xml -XPath "//store[folder[contains(.,'$search')]]" |Select-Object -Expand Node

答案 1 :(得分:0)

当然,只需选择所有商店并使用Where-Object cmdlet过滤文件夹子包含特定值的商店:

[xml]$content = Get-Content 'your_xml'
$content.mailmanager.locations.store | 
    Where-Object { $_.folder -eq '\\site.domain.com\legal\01038\documents\' }

<强>输出:

id          : 6873a00e-e49c-4602-af27-49d2900563d3
type        : msg
description : 01038 - Wood Wharf - Fire
folder      : \\site.domain.com\legal\01038\documents\
fileable    : 0

答案 2 :(得分:0)

您可以使用XPath:

$document = New-Object System.Xml.XPath.XPathDocument("C:\Path\To\XmlFile.xml")
$navigator = $document.CreateNavigator()
$navigator.Select("//store[folder='SharePoint:https://site.domain.com/legal/01038/documents/Forms/CRMView.aspx']")