Сценарий InDesign CS5: как можно игнорировать DTD при импорте XML?
Я импортирую XML в InDesign и получаю следующее сообщение:
Внешняя сущность 'blahblah.dtd' не может быть найдена. Продолжить импорт в любом случае?
И когда я продолжаю импортировать XML, я получаю следующее сообщение об ошибке:
Ошибка JavaScript!
Номер ошибки: 103237 Строка ошибки: ошибка преобразования DOM: недопустимое пространство имен.
Движок: сессия Файл: C:\blahblah\blahblah.jsx Строка: 259 Источник:
obj.doc.importXML (File (xmlDoc));
... проблема в том, что у меня не будет доступа к DTD, и в любом случае он мне не понадобится для моих целей.
- Итак, есть ли способ Extendscript игнорировать DTD?
- Если нет, есть ли способ игнорировать DTD с помощью XSLT?
Вот соответствующий код:
function importXML(xmlDoc, xslt)
{
with(obj.doc.xmlImportPreferences)
{
importStyle = XMLImportStyles.MERGE_IMPORT; // merges XML elements into the InDesign document, merging with whatever matching content
createLinkToXML = true; // link elements to the XML source, instead of embedding the XML
// defining the XSL transformation settings here
allowTransform = true; // allows XSL transformation
transformFilename = File(xslt); // applying the XSL here
repeatTextElements = true; // repeating text elements inherit the formatting applied to placeholder text, **only when import style is merge!
ignoreWhitespace = true; // gets rid of whitespace-only text-nodes, and NOT whitespace in Strings
ignoreComments = true;
ignoreUnmatchedIncoming = true; // ignores elements that do not match the existing structure, **only when import style is merge!
importCALSTables = true; // imports CALS tables as InDesign tables
importTextIntoTables = true; // imports text into tables if tags match placeholder tables and their cells, **only when import style is merge!
importToSelected = false; // import the XML at the root element
removeUnmatchedExisting = false;
}
obj.doc.importXML(File(xmlDoc) );
obj.doc.mapXMLTagsToStyles(); // automatically match all tags to styles by name (after XSL transformation)
alert("The XML file " + xmlDoc.name + " has been successfully imported!");
} // end of function importXML
... это основано на с. 407 (глава 18) автоматизации InDesign CS5 с использованием XML и Javascript, автор Grant Gamble
3 ответа
Хорошо, даже проще. Мы просто должны предотвратить взаимодействие, а затем удалить все прикрепленные dtds:
function silentXMLImport(file)
{
var doc, oldInteractionPrefs = app.scriptPreferences.userInteractionLevel;
if ( !(file instanceof File) || !file.exists )
{
alert("Problem with file : "+file );
}
if ( app.documents.length == 0 )
{
alert("Open a document first");
return;
}
//Prevent interaction and warnings
app.scriptPreferences.userInteractionLevel = UserInteractionLevels.NEVER_INTERACT;
doc = app.activeDocument;
doc.importXML ( file );
//Remove any dtd attached to the document
doc.dtds.everyItem().remove();
app.scriptPreferences.userInteractionLevel = oldInteractionPrefs;
}
//Now import xml
silentXMLImport ( File ( Folder.desktop+"/foobar.xml" ) );
Это работает здесь.
Вот XSLT, который удалит объявление DOCTYPE:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<xsl:copy-of select="."/>
</xsl:template>
</xsl:stylesheet>
Я думаю, что zanegray дал вам основную концепцию, хотя я думаю, что вы слишком усложняете вещи. Почему бы просто не получить содержимое XML-файла, удалить объявление dtd с помощью регулярного выражения и затем вывести новый XML-файл, который будет использоваться для ввода?
//Open and retrieve original xml file content
var originalXMLFile = File (Folder.desktop+"/foo.xml" );
originalXMLFile.open('r');
var content = originalXMLFile.read();
//Looks for a DOCTYPE declaration and remove it
content = content.replace ( /\n<!DOCTYPE[^\]]+\]>/g , "" );
originalXMLFile.close();
//Creates a new file without any DTD declaration
var outputFile = new File ( Folder.desktop+"/bar.xml" );
outputFile.open('w');
outputFile.write(content);
outputFile.close();
Затем вы можете использовать этот отфильтрованный XML для вашего импорта.