0

I have an XML file looks like this :

<?xml version="1.0" encoding="UTF-8"?>
<INITIAL>
    <FB1>a</FB1>
    <FB2>b</FB2>
    <FB3>c</FB3>
    <FB4>d</FB4>
    <FB5>e</FB5>
    <FB6>f</FB6>
    <FB7>g</FB7>
    <FB8>h</FB8>
    <FB9>i</FB9>

</INITIAL>

I just want to read element a to iand convert it to string, be like this :

abcdefghi
Job
  • 415
  • 1
  • 11
  • 31

3 Answers3

0

You first create an System.Xml.XmlDocument out of it. Here is an example:

$theXml = [xml](gc $xmlPath)
$theXml.GetType().fullname

Once you have it, you can play-around the way you want! - In your example, you need concatenation of values of child elements. You would find lot of example online how to concatenate string values from an Array - example

$theXml.INITIAL.GetEnumerator() # this gives you enumeration of values in children to the 'INITIAL' element. 

I Hope this helps.

Edit: And yeah, your xml was broken - I assume it added closing tags like </FB1> for all.

Ketanbhut
  • 476
  • 2
  • 11
  • I tried this : $XML = [xml](gc "C:\Users\XML.xml") $XML.GetType().FullName It error : Cannot convert value System.Object[] to type System.Xml.XmlDocument. This document already has a DocumentElement node – Job Mar 11 '19 at 08:45
0

You can use an XPath expression to get the nodes you want and then use the -join operator to join the strings together.

The XPath expression /INITIAL/* means every element directly inside the INITIAL element at top level. Taking care to select the data you actually want will help you if someone later decides to extend the data format somehow.

PS> $Data = New-Object Xml
PS> $Data.Load((Resolve-Path file.xml))

PS> $Data.SelectNodes("/INITIAL/*")."#text" -join ""
frfsftfufvfwfhgKfg

Tested with Windows PowerShell 5.1 on Windows 10.

Don Cruickshank
  • 5,641
  • 6
  • 48
  • 48
  • Using SelectNodes is error : Exception calling "SelectNodes" with "1" argument(s): "Expression must evaluate to a node-set." – Job Mar 11 '19 at 09:00
  • @Job - the XPath query in my answer creates a node-set. What is the actual query you're using? – Don Cruickshank Mar 11 '19 at 10:28
0

Assuming this XML:

<INITIAL>
    <FB1>fr</FB1>
    <FB2>fs</FB2>
    <FB3>...</FB3>
</INITIAL>

fetching the InnerText of the container element will be enough:

Write-Host $xml.DocumentElement.InnerText

This would print frfs....

If in your actual XML the container isn't the top-most element, substitute DocumentElement with .SelectSingleNode('some/xpath').

Tomalak
  • 332,285
  • 67
  • 532
  • 628