我正在编写一个脚本,使用 After Effects 和 Extendscript 将一些 xml 数据更新到现有文件中。我正在尝试将新元素添加到现有文件中。我有以下代码:
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();
}
但是这段代码用新元素替换了文档中的所有文本,所以我尝试使用像“标记”这样的 xml 注释在它下面插入元素。这是 xml:
<Root>
<child name="ChildOne"/>
<child name="ChildTwo"/>
<!---->
</Root>
代码:
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();
}
这段代码在正确的位置写入了删除符,但它从下一行删除了一些字符,如下所示:
<Root>
<child name="ChildOne" />
<child name="ChildTwo" />
<!---->
<child name="ChildThree">
ot>
我的问题是:为什么会这样?有没有合适的方法来实现这一目标? 谢谢。
最佳答案
Why is this happening?
您正在尝试使用 seek
和 writeln
将一行插入到现有文件中。不幸的是,这根本不是文件的工作原理。您不能插入单个字节 - 更不用说整行了。
Is there a proper way to achieve this?
是的,有多种方式。
例如:打开这个文件进行读取,打开一个新的文件进行写入。从此文件中逐行读取并将其写入新文件。如果遇到标记,请插入新行。完成后,删除旧文件并重命名新文件。
关于javascript - 如何在 extendscript 中将新元素添加到现有 XML 文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31560874/