kafka
kafka

Reputation: 568

Why is Powershell not treating my file as a well formed XML document?

I'm trying to create a Powershell script which simply recurses through a directory, pulling out the XML files. Then we loop through each of the XMLs, and I simply want to return the count of a certain node. Straight forward stuff. However I can't get it working, and it isn't loading the child nodes correctly.

Here is my code:

foreach ($file in $xmlFiles)
{       
$xml = [xml](Get-Content $file)
$xml.SelectNodes("//RootNode/NextNode")
Write-Host $xml.count    
}

The problem, I believe, doesn't lie with the code, but possibly the XML file itself. If I do a $xml.ChildNodes I get:

xmlns                        NextNode
_____                        _____
http://urlgoeshere           NextNode

where the first item is an attribute of the root node, specifically the schema information; the second item is the next node down from the root. There are more nodes though, which won't show up. The XML is well formed, as it's generated by one program and used by another. However, ChildNodes just isn't displaying all nodes.

<ScreeningSubmission xmlns="http://schema/">
<submission version="2.0">    
<patient>
  <firstname></firstname>
  <lastname></lastname>
  <gender></gender>
  <date-of-birth></date-of-birth>
  <ethnicity></ethnicity>
  <client_ref></client_ref>
  <address1></address1>
  <address2></address2>
  <address3></address3>
  <postcode> </postcode>
  <telephone></telephone>
  <events>
    <result>
      <date></date>
      <read2></read2>
      <value></value>
      <units></units>
      <term30></term30>
      <term60></term60>
    </result>        
  </events>
</patient>
</submission>
</ScreeningSubmission>

Essentially I want to count the number of the node - there is generally about 10+ of this node.

Upvotes: 0

Views: 376

Answers (3)

stej
stej

Reputation: 29449

You might forget about XPath if it is not necessary and use direct access:

$xml = [xml](Get-Content $file)
$xml.ScreeningSubmission.submission.patient.ChildNodes.Count

Upvotes: 1

Szymon Kuzniak
Szymon Kuzniak

Reputation: 858

Check if your schema definition is correct. It worked for me when I have removed it.

Upvotes: 0

Szymon Kuzniak
Szymon Kuzniak

Reputation: 858

You should assign result of SelectNodes into a variable. You will get a list so you can then write number of the elements using count.

$nodes = $xml.SelectNodes("//RootNode/NextNode")
Write-Host $nodes.count

You can also query for nodes count using following statement

$xml.ScreeningSubmission.ChildNodes.Count

Upvotes: 0

Related Questions