views:

96

answers:

2

How to read the below xml file and write its content into a plain text file?

<!--
< config >
 < compare >
  < source >d:\demo\< /source >
  < destination >e:\demo\< / destination >
  < parameters >
   < parameter >FileName< /parameter>
   < parameter >Size< /parameter>
   < parameter>Date< /parameter>
  < /parameters >
 < /compare >
 < compare >
  < source >d:\sample\< /source >
  < destination >e:\sample\< /destination >
  < parameters >
   < parameter >Name< /parameter >
   < parameter >FullName< /parameter >
   < parameter >version< /parameter >
   < parameter >culture< /parameter >
  < /parameters >
 < /compare >
< /config >
-->

Desired Output:

d:\demo   e:\demo  FileName  Size  Date
d:\sample   e:\sample  Name  FullName  Version Culture
A: 

This is a great article on how to manipulate XML from PowerShell.

Traveling Tech Guy
+1  A: 

Well, your comment around your XML is going to cause some parsing issues - but for the sake of answering the question, I am going to assume it isn't actually there in real life. The easiest way to deal with XML in PowerShell is to treat it as a string, and cast it to an XML object:

$xml = [xml](Get-Content c:\temp\config.xml)

Now that you have an xml variable, you can do cool things like:

$xml.config.compare.source

Which will put the string "d:\demo\" in the pipeline, and in this case no further processing takes place and it outputs it. Grabbing the other elements should be pretty straightforward, though the multiple parameter tags are treated similarly to an array:

$xml.config.compare.parameters.parameter[0]

Writing output can be as easy as just redirecting the output:

$xml.config.compare.source >> c:\temp\output.txt

The single greater than sign will overwrite the contents of the file, the double is used for appending.

Goyuix