Reputation: 787
I'm writing a script to update some xml data into an existing file with After Effects and Extendscript.I'm trying to add new elements into the existing file.I have this code:
function writeXml (xml)
{
var file = new File(filePath);
if (!(xml instanceof XML))
{
throw "Bad XML parameter";
}
file.encoding = "UTF8";
file.open("e");
file.write("\uFEFF");
file.lineFeed = "windows";
file.write(xml.toXMLString());
file.close();
}
But this code replace all the text inside the document with the new element, so I tryed to use an xml comment like a 'marker' to insert the element below it. Heres is the xml:
<Root>
<child name="ChildOne"/>
<child name="ChildTwo"/>
<!---->
</Root>
The code:
function writeXml (xml)
{
var file = new File(filePath);
var fileOk = file.open("e");
var strLine, line, docPos;
if (!(xml instanceof XML))
{
throw "Bad XML parameter";
}
if (!fileOk)
{
throw "Cant open file";
}
file.encoding = "UTF8";
while (!file.eof)
{
strLine = file.readln();
docPos= strLine.search("<!---->");
if (docPos!= -1)
{
file.seek(0, 1);
file.writeln("<!----> \n");
break;
}
}
file.close();
}
This code write's the elmemnt in the correct position but it deletes some characters from the next line, like this:
<Root>
<child name="ChildOne" />
<child name="ChildTwo" />
<!---->
<child name="ChildThree">
ot>
My questions are: Why is this happening? and Is there a proper way to achieve this? Thanks.
Upvotes: 1
Views: 408
Reputation: 22457
Why is this happening?
You are trying to insert a line into an existing file with that seek
and writeln
. Unfortunately, that simply is not How Files Work. You cannot insert a single byte - let alone an entire line.
Is there a proper way to achieve this?
Yes, there are various ways.
For example: Open this file for reading, and a new one for writing. Read per line from this file and write it to your new file. If you come across your marker, insert your new line. When done, delete the old file and rename the new one.
Upvotes: 2
Reputation: 787
I found a solution,it looks pretty ugly but it works:
function writeXml (xml)
{
var file = new File(filePath);
var fileOk = file.open("e");
var strLine, line, docPos, marker;
marker = "<!---->";
if (!(xml instanceof XML))
{
throw "Bad XML parameter";
}
if (!fileOk)
{
throw "Cant open file";
}
while (!file.eof)
{
strLine = file.readln();
docPos= strLine.search(marker);
if (docPos!= -1)
{
file.seek( (-marker.length - 2), 1);
file.writeln(xml + "\n" + marker + "\n</Root>");
break;
}
}
file.close();
}
Upvotes: 0