1

I have a string in an XML which I am trying to retrun to a varable (below).

<XMLElement><![CDATA[TEXT - I - FIND - INTERESTING]]></XMLElement>

My problem is that I have no knowledge of regex and I am finding it difficult to understand how to convert my special characters into a "string" which is not interpreted as a regex charater.

The text between the square brackets can be any length and any charachter; this is what I would like to save to my variable e.g. "TEXT - I - FIND - INTERESTING".

I am also wondering if this is actually the best approach to this problem.

Any support would be greatly appreciated.

2
  • I don't know Powershell, but maybe.... regex101.com/r/FEumVc/1. The text of interest would be in group 1. Commented Mar 25, 2020 at 22:00
  • @MDR thank you. I will update my question with the answer. This was exactly what I needed. Commented Mar 25, 2020 at 22:11

2 Answers 2

3

Don't use regex for XML!

Working with XML in PowerShell has the advantage that we can use XPath to search and navigate a document. In your case I would use the text() selector to resolve the inner value of the CDATA section:

$xml = [xml]@'
<root>
    <XMLElement><![CDATA[TEXT - I - FIND - INTERESTING]]></XMLElement>
</root>
'@

$interestingString = $xml.SelectSingleNode('//XMLElement/text()').Value

//XMLElement means "find and <XMLElement> anywhere"

Sign up to request clarification or add additional context in comments.

3 Comments

Is there a way to select just the text from an attribute? This just returns nothing: "<XMLElement attrib='this'></XMLElement>" | select-xml '/XMLElement/@attrib/text()' | % node
@js2010 no, the expression has to resolve a "node set", in this case consisting only of the <![CDATA]> node
Thanks Mathias, that works a treat and something I can understand better what I am looking at :)
0

The text() function is nice. Here's another way. Even if the node isn't at the top, this should work.

get-content -raw file.xml | select-xml '//XMLElement' | 
  % { $_.node.'#cdata-section' }

TEXT - I - FIND - INTERESTING

Note that tags would be ignored in a cdata section. Example:

'<script>
  <![CDATA[<message>Welcome to TutorialsPoint</message>]]>
</script>' | select-xml '/script' | % { $_.node.'#cdata-section' }

<message>Welcome to TutorialsPoint</message>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.