0

I have code that for all intents and purposes follows the following format for a bunch of users. I need to be able to extract just the email part of the XML in Powershell. How would I do that? The indentation is messed up, I know and am sorry.

<user>
<primary_id>jd112</primary_id>
<first_name>John</first_name>
<middle_name/>
<last_name>Doe</last_name>
<full_name>John Doe</full_name>
-<contact_info>
-<addresses>
-<emails>
<email_address>john.doe@main.com</email_address>
</email>
</emails>
</addresses>
</contact_info>

</user>
Ken White
  • 123,280
  • 14
  • 225
  • 444
Leigh
  • 11
  • 1
  • 2
    Your XML isn't well-formed, due to the stray ``. Are the `-` characters really a part of the document? Please [edit] your question to fix the XML and show what you have tried so far and where, specifically, you're stuck. – mklement0 Oct 10 '22 at 22:22
  • 1
    You can use `Select-Xml` for it. Something like `Select-Xml -Xml $MyXml -XPath '//email_address' |%{$_.Node.'#text'}` – TheMadTechnician Oct 10 '22 at 22:55
  • Function to format xml: https://stackoverflow.com/a/47947373/6654942 – js2010 Oct 10 '22 at 23:25

1 Answers1

0

Try following :

using assembly System.Xml.Linq
$xDoc = [System.Xml.Linq.XDocument]::Load('c:\temp\test.xml')
$user = $xDoc.Root

$primary = $user.Element("primary_id").Value
$first_name = $user.Element("first_name").Value
$middle_name = $user.Element("middle_name").Value
$last_name = $user.Element("last_name").Value
$full_name= $user.Element("full_name").Value

$emails_address = [System.Linq.Enumerable]::First($user.Descendants("email_address"))
$emails_address = [System.Xml.Linq.XElement]$emails_address
$emails_address = $emails_address.Value



Write-Output $primary_id
Write-Output $first_name
Write-Output $middle_name
Write-Output $last_name
Write-Output $full_name
Write-Output $emails_address
Write-Output $email
jdweng
  • 33,250
  • 2
  • 15
  • 20