1

I want to do mapping using XML document. I use method contain to map. I tried this code:

$ID_Unit = "1234"
$Flag_Path = "D:\Auto\File602.XML"
[xml]$Read = Get-Content $Flag_Path
$All_ID = $Read.Title.Unit

$Map_ID = $All_ID | Where-Object {$_.Contains("$ID_Unit")}

if ($Map_ID) {
    Write-Host "Match"
} else {
    Write-Host "Not Match"
}

but it returns this error:

Method invocation failed because [System.Xml.XmlElement] does not contain a method named 'Contains'.

This is my XML documents looks like:

<?xml version="1.0" encoding="UTF-8"?>
<Title>
    <Unit>
        <ID1>1234</ID1>
        <ID2>5678</ID2>
    </Unit>
</Title>
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Job
  • 415
  • 1
  • 11
  • 31

1 Answers1

1

As Mathias R. Jessen in above comment, you can use XPath to check for a specific value (instead of PowerShells -contains operator).

Example:

$ID_Unit = "1234"
$xml = [xml] (Get-Content "test.xml")
$units = @($xml.SelectNodes("//Unit/*[text()=$ID_Unit]"))
if ($units.Count -gt 0){
    Write-Host "Text found"
}

This stackoverflow answer gives an explantion of the difference of the XPATh . and text() operations.

Moerwald
  • 10,448
  • 9
  • 43
  • 83