Проблема при выполнении файла XSLT-преобразования в JavaScript XUL - PullRequest
1 голос
/ 19 июля 2011

Я работаю над XUL и пытаюсь выполнить функцию процессора XSLT в XUL с использованием JavaScript.

У меня есть функция JavaScript, с помощью которой я могу обновить новую запись в своем XML-файле и сохранить XMLфайл.После этого я пытаюсь выполнить функцию процессора XSLT, но не могу загрузить свои файлы XSL и XML.

Моя рабочая среда в окнах - Eclipse, XulBooster.Как правило, для загрузки любого файла, который я использую («File: // C: /mercredi.xml») или («C: /mercredi.xml»);оба пути к файлам отлично работают в других функциях, даже в функции JavaScript, которую я использовал по одному и тому же пути к файлу для чтения и сохранения файла XML.

1.Я скопировал следующий код Листинг6: с этого веб-сайта:
http://www.ibm.com/developerworks/xml/library/x-ffox3/index.html

function process()
{
//Create an XSLT processor instance
var processor = new XSLTProcessor();
//Create an empty XML document for the XSLT transform
var transform = document.implementation.createDocument("", "", null);
//Load the XSLT
transform.onload = loadTransform;
transform.load("file://C:/idgenerator.xsl");

//Triggered once the XSLT document is loaded
function loadTransform(){
  //Attach the transform to the processor
  processor.importStylesheet(transform);
  source = document.implementation.createDocument("", "", null);
  source.load("file://C:/mercredi.xml");
  source.onload = runTransform;
}

//Triggered once the source document is loaded
function runTransform(){
  //Run the transform, creating a fragment output subtree that
  //can be inserted back into the main page document object (given
  //in the second argument)
  var frag = processor.transformToFragment(source, document);

}
}

Затем я проверил сайт Mozilla и следовал инструкциям, но все равно не смог загрузить свой файл.2. Следующий код скопирован с этого сайта: https://developer.mozilla.org/en/Using_the_Mozilla_JavaScript_interface_to_XSL_Transformations

Даже в этой функции я не смог загрузить свой XML-файл.

function xslt()
{
var processor = new XSLTProcessor();

var testTransform = document.implementation.createDocument("", "test", null);
// just an example to get a transform into a script as a DOM
// XMLDocument.load is asynchronous, so all processing happens in the
// onload handler
testTransform.addEventListener("load", onload, false);
testTransform.load("file://C:/mercredi.xml");
function onload() {
  processor.importStylesheet(testTransform);
}
}

Это мой код JavaScript для выполненияФункция process () процессора XSLT.

function saveFile(output, savefile) {

    //function from http://puna.net.nz/archives/Code/Mozilla%20XUL%20LOG%20-%20read%20local%20files%20and%20write%20local%20files.htm
    //var savefile = "c:\\mozdata.txt";

    try {
        netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
    } catch (e) {
        alert("Permission to save file was denied.");
    }
    var file = Components.classes["@mozilla.org/file/local;1"]
        .createInstance(Components.interfaces.nsILocalFile);
    file.initWithPath( savefile );
    if ( file.exists() == false ) {
        alert( "File Updated Successfully ");
        file.create( Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 420 );
    }
    var outputStream = Components.classes["@mozilla.org/network/file-output-stream;1"]
        .createInstance( Components.interfaces.nsIFileOutputStream );
    /* Open flags
    #define PR_RDONLY       0x01
    #define PR_WRONLY       0x02
    #define PR_RDWR         0x04
    #define PR_CREATE_FILE  0x08
    #define PR_APPEND      0x10
    #define PR_TRUNCATE     0x20
    #define PR_SYNC         0x40
    #define PR_EXCL         0x80
    */
    /*
    ** File modes ....
    **
    ** CAVEAT: 'mode' is currently only applicable on UNIX platforms.
    ** The 'mode' argument may be ignored by PR_Open on other platforms.
    **
    **   00400   Read by owner.
    **   00200   Write by owner.
    **   00100   Execute (search if a directory) by owner.
    **   00040   Read by group.
    **   00020   Write by group.
    **   00010   Execute by group.
    **   00004   Read by others.
    **   00002   Write by others
    **   00001   Execute by others.
    **
    */
    outputStream.init( file, 0x04 | 0x08 | 0x20, 420, 0 );
    var result = outputStream.write( output, output.length );
    outputStream.close();
alert( "File Updated Successfully ");
clear();
process();

}

Почему я хочу выполнить файл XSLT в моем XUL?заключается в создании уникального идентификатора для моего клиента в файле XML.

Пожалуйста, помогите мне Что я здесь не так делаю?!?Большое спасибо.

Это мой XSLT-файл:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="CONTACT">
        <xsl:copy>
               <Customer-Id>
               <xsl:value-of select="generate-id(.)"/> 
               </Customer-Id>
              <xsl:copy-of select="FirstName|LastName|gmail|yahoo| Hotmail |URL|Facebook-ID"/>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

1 Ответ

0 голосов
/ 20 июля 2011

По некоторым причинам это:

var testTransform = document.implementation.createDocument("", "test", null);

и

testTransform.addEventListener("load", onload, false);testTransform.load("file://C:/mercredi.xml");

это не сработало.

Затем я понял, что использую функцию 'readFile'в моем JavaScript, чтобы загрузить файл.Я использовал эту функцию для загрузки любого файла в XUL.

Вот код:

function process()
{ 
    var src = readFile("c:\\idgenerator.xsl");//load my XSl file
    var parsed = (new DOMParser()).parseFromString(src, "text/xml");
    var stylesheet = parsed.documentElement;
    var processor = new XSLTProcessor();
    processor.importStylesheet(stylesheet );

    objXMLDoc = processor.transformToDocument(objXMLDoc);//load & transform my XML file

    var serializer = new XMLSerializer();
    var prettyString = serializer.serializeToString(objXMLDoc);
    saveFile(prettyString, "C:\\mercredi.xml");//Save the XML file
} 
...