Parsing XML

I’m working with DISA STIGs to harden Server 2012 R2. The STIGS use XML files to analyze how compliant the server is. I’m new to working with XML but I’m trying to create a psobject using that XML file and it mostly works. I’ve created the $xml variable as shown below:

[xml] $xml = Get-Content -Path stig.xml

The description for each rule in the STIG is a string with XML tags under $xml.benchmark.group.rule.description. I want to pull out those tags and be able to do .description.vulnDiscussion. The example XML is below:

https://gist.github.com/camusicjunkie/b96fa7a853fda3091c68f12f6c2c0d41

I’ve tried using ConvertTo-Xml with no luck. It maintains the object as a string. I’ve also tried

[xml] $xml.benchmark.group.rule.description

and I get the error

Cannot convert value "System.Object[]" to type "System.Xml.XmlDocument". Error: "This document already has a 'DocumentElement' node."

I’m at a loss on how to convert that string to XML. Any ideas?

Any html/xml content need to be stored somewhere else.
E.g. in Gist and post a link to it.

I’ve added the XML example using Gist.

$xml.save('whatever.xml')

It makes it prettier too.

The error is coming from the fact that there’s no root node. For whatever reason, the STIG guide saves that description info as a string ready to be parsed back into XML instead of having it encoded as part of the rest of the checklist’s XML. If you want to turn it back into something the [xml] accelerator can parse, you have to wrap it in a parent node. Something like this should work:

$Description = $xml.benchmark.group[0].rule.description
[xml] "${Description}" | Select-Object -ExpandProperty root

I named the node ‘root’ there, but it really doesn’t matter since you’re just using it as a way to wrap all of the text in the ‘description’.

You didn’t post anything that wraps that xml with a root node or am I just not understanding here?

EDIT: Nevermind. I figured out what you were saying.
https://gist.github.com/camusicjunkie/a390c2a638e796bfd45ded65cfc3fad2
I still don’t quite understand why this works but it works. Thanks for your help!

Ha! I always forget that the forum strips out tags. I’m going to repost it below, but replace the brackets around the [root] with less than and greater than signs:

$Description = $xml.benchmark.group[0].rule.description
[xml] "[root]${Description}[/root]" | Select-Object -ExpandProperty root

Edit: I see you already figured it out :slight_smile: Glad it’s working!

convertto-xml just turns some other powershell object into an [xml] object. $xml.save() will make xml text, if that’s what you’re trying to do.