如何在powershell中解析XML以搜索要删除的标记?

时间:2013-08-15 09:16:45

标签: xml parsing powershell

我有以下xml:

<?xml version="1.0" encoding="utf-8"?>
<ManagementPack ContentReadable="true" SchemaVersion="2.0" OriginalSchemaVersion="1.0" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<Reference Alias="MicrosoftSystemCenterNetworkDeviceLibrary6172210">
        <ID>Microsoft.SystemCenter.NetworkDevice.Library</ID>
        <Version>7.0.9538.0</Version>
        <PublicKeyToken>31bf3856ad364e35</PublicKeyToken>
      </Reference>
<DisplayString ElementID="SC_e307a242ac6341079fb4e6446bd2ae05_Service_b7434c612faf4f488b33dc409a2cdd1a">
          <Name>name1</Name>
</DisplayString>
<DisplayString ElementID="SCIMembership_029d2e1209624b97af70462cb18aac4a_HealthMonitor">
       <Name>Component Group Health Roll-up for type Target Host</Name>
        <Description>The health of this Component is determined by the health of its members. This monitor rolls up health from each of the members of this Component.

    </Description>
    </DisplayString>
     <DisplayString ElementID="SC_7ece04875a51404db40b704244605b74_Service_b7434c612faf4f488b33dc409a2cdd1a">
              <Name>name2</Name>
    </DisplayString>
            <DisplayString ElementID="SCIMembership_04137e55024b4bc9a436668abc878d19_HealthMonitor">
              <Name>Component Group Health Roll-up for type Target Host</Name>
              <Description>The health of this Component is determined by the health of its members. This monitor rolls up health from each of the members of this Component.</Description>
            </DisplayString>
    <Reference Alias="MicrosoftSystemCenterNetworkDeviceLibrary6172210">
            <ID>Microsoft.SystemCenter.NetworkDevice.Library</ID>
            <Version>7.0.9538.0</Version>
            <PublicKeyToken>31bf3856ad364e35</PublicKeyToken>
          </Reference>
    </ManagementPack>

我有一个带搜索字符串的txt文件:

  

SCIMembership_86a804b4c89148749da13e192240dc5f   SCIMembership_f833b674da494d42b778637e89bbaca4   SCIMembership_029d2e1209624b97af70462cb18aac4a   SCIMembership_c4c478aa4f75481b82a0263e5fd4107a

我们还定义了$tagname = DisplayString

我需要为这些搜索字符串解析xml并删除整个$ tagname(如果它存在)。它可以在ElementID中,也可以在任何地方,所以如果它在标签DisplayString中,我们找到了搜索字符串 - 我们应该删除它。

我尝试过循环,但对我来说主要问题是如何搜索项目/标签。

1 个答案:

答案 0 :(得分:0)

试试这个:

$tagname = "DisplayString"
$xml= [xml] (Get-Content .\myxml.xml)#Read your xml
$serachString=[Io.File]::ReadAllText(".\mystr.txt")#Read search string text file
foreach ($node in $xml.ManagementPack.$tagname) {
    if ($serachString.Contains($node.ElementID)){$xml.ManagementPack.RemoveChild($node)}
}
$xml.Save(".\myxml.xml")