Reputation: 1345
I'm currently creating a script that will turn a CSV file into an XML document. I have the following:
function writeDoc(){
$XmlWriter.WriteStartElement("RootElement")
foreach($test in $csvFile)
{
$valueArr+= $test.id
$valueArr+=$test.first_name
$valueArr+= $test.last_name
$valueArr+= $test.email
$valueArr+= $test.country
$valueArr+= $test.ip_address
addElementToDoc("Person")
$valueArr = @()
}
# close root
$XmlWriter.WriteEndElement()
# close doc
$XmlWriter.WriteEndDocument()
$XmlWriter.Finalize
$XmlWriter.flush()
$XmlWriter.Close()
}
function addElementToDoc($elName)
{
$XmlWriter.WriteStartElement($elName)
for($i=0;$i -le $headerArr.Length; $i++)
{
$XmlWriter.WriteElementString($headerArr[$i], $valueArr[$i])
}
$XmlWriter.WriteEndElement()
}
function setupXmlWriter()
{
# set formatting
$XmlWriter.formatting = "Indented"
$XmlWriter.Indentation = "4"
#write xml declaration
$XmlWriter.WriteStartDocument()
#set the xsl
$XSLPropText = "type='text/xsl' href='style.xsl'"
$XmlWriter.WriteProcessingInstruction("xml-stylesheet", $XSLPropText)
}
The csv contains columns id, fname, lname, email, coutnry and ip address. when Converting the document, everything is fine until it reaches ip address. The finished element ends up looking like this:
<Person>
<id>2</id>
<first_name>Bonnie</first_name>
<last_name>Gomez</last_name>
<email>[email protected]</email>
<country>Portugal</country>
<ip_address
>165.233.249.20</ip_address
>
</Person>
Is there a way to prevent the last element from taking a new line? I have tried running the addElementToDoc()
function without writing ip address and the formatting is fine, it only occurs whenever the writer writes the ip address and value.
Is there something I've missed? or maybe a formatting parameter I should have set/have set incorrectly?
Upvotes: 2
Views: 274
Reputation: 7783
You have an array out-of-bounds mistake right here:
for($i=0;$i -le $headerArr.Length; $i++)
{
$XmlWriter.WriteElementString($headerArr[$i], $valueArr[$i])
}
Since $i
runs from 0
up to $headerArr.Length
because of the -le
(less or equal, i.e. <=). This may cause the unexpected output.
Use this instead:
for($i=0; $i -lt $headerArr.Length; $i++)
{
$XmlWriter.WriteElementString($headerArr[$i], $valueArr[$i])
}
Upvotes: 2