OpenOffice.org Forum at OOoForum.orgThe OpenOffice.org Forum
 
 [Home]   [FAQ]   [Search]   [Memberlist]   [Usergroups]   [Register
 [Profile]   [Log in to check your private messages]   [Log in

Writing directly XML Instructions in a Document (C++, Basic)

 
Post new topic   Reply to topic    OOoForum.org Forum Index -> OpenOffice.org Code Snippets
View previous topic :: View next topic  
Author Message
SergeM
Super User
Super User


Joined: 09 Sep 2003
Posts: 3211
Location: Troyes France

PostPosted: Wed Aug 30, 2006 11:56 am    Post subject: Writing directly XML Instructions in a Document (C++, Basic) Reply with quote

This thread is related to Using UNO's Xml sax parser via the API in C++ [url]http://www.oooforum.org/forum/viewtopic.phtml?t=42387[/url] but different enough to be in a separate thread. In fact both threads together could be used to construct a XML import in OOo without XLST. I will construct such a synthese later on...
(Sorry for the listing numeration here !)
Our goal is very well described in the comments of the Listing 9 below (given again in Listing 8 ) : load a XML description in a document which gives the famous Hello World! in a writer document.
The difficulty is, we don't want to see all the Listing 8 in our writer document but only the text Hello World! as a paragraph : this is the signification of the corresponding XML text.

Listing 8 What we would want to send in a Writer Document for interpretation
Code:

<office:document
      office:class="text"
      xmlns:office="http://openoffice.org/2000/office"
      xmlns:text="http://openoffice.org/2000/text" >
   <office:body>
     <text:p>Hello World!</text:p>
   </office:body>
</office:document>


I provide now the code from the article "OpenOffice.org filters using the XML based file format" [url]http://xml.openoffice.org/filter/ [/url]
where I have added comments which shows the little errors in the code. If you want to construct the automation program, don't take into acount this code, it's only given for the start. It was the only documentation I have when I started this project.
Code:

//Listing 9 http://xml.openoffice.org/filter/Code
// C++
using namespace ::com::sun::star;

// instantiate the XML import component !!!! fell a ';' !!!!
::rtl::OUString sService =
    ::rtl::OUString::createFromAscii("com.sun.star.comp.Writer.XMLImporter")
// !!!!!!!!! xHandler instead of xImport because xHandler is used below
uno::Reference<xml::sax::XDocumentHandler> xImport(
    xServiceFactory->createInstance(sService), uno::UNO_QUERY );
ASSERT( xImport.is(), "can't instantiate XML import" );

// OK. Now we have the import. Let's make a real simple document.

// a few comments:
// 1. We will use string constants from xmloff/xmlkywd.hxx
// 2. For convenience, we'll use a globally shared attribute list from the
//    xmloff project (xmloff/attrlist.hxx)
// 3. In a real project, we would pre-construct our OUString, rather than use
//    the slow createFromAscii() method every time.

// We will write the following document: (the unavoidable 'Hello World!')
// <office:document
//      office:class="text"
//      xmlns:office="http://openoffice.org/2000/office"
//      xmlns:text="http://openoffice.org/2000/text" >
//   <office:body>
//     <text:p>Hello World!</text:p>
//   </office:body>
// </office:document>

SvXMLAttributeList aAttrList;

xHandler->startDocument();

// our first element: first build up the attribute list, then start the element
// DON'T FORGET TO ADD THE NAMESPACES!
aAttrList.AddAttribute(
    ::rtl::OUString::createFromAscii("xmlns:office"),
    ::rtl::OUString::createFromAscii("CDATA"),
    ::rtl::OUString::createFromAscii("http://openoffice.org/2000/office") );
aAttrList.AddAttribute(
    ::rtl::OUString::createFromAscii("xmlns:text"),
    ::rtl::OUString::createFromAscii("CDATA"),
    ::rtl::OUString::createFromAscii("http://openoffice.org/2000/text") );
aAttrList.AddAttribute(
    ::rtl::OUString::createFromAscii("office:class"),
    ::rtl::OUString::createFromAscii("CDATA"),
        ::rtl::OUString::createFromAscii("text") );
xHandler->startElement(
    ::rtl::OUString::createFromAscii("office:document"),
    aAttrList );

// body element (no attributes)
aAttrList.clear();
xHandler->startElement(
    ::rtl::OUString::createFromAscii("office:body"),
    aAtrList );

// paragraph element (no attributes)
aAttrList.clear();
xHandler->startElement(
    ::rtl::OUString::createFromAscii("text:p"),
    aAtrList );

// write text
xHandler->characters(
    ::rtl::OUString::createFromAscii("Hello World!") );

// close paragraph !!!!!!! Error here ',' instead of ';' !!!!!
xHandler->startElement(
    ::rtl::OUString::createFromAscii("text:p"),

// close body
xHandler->endElement(
    ::rtl::OUString::createFromAscii("office:body") );

// close document element
xHandler->endElement(
    ::rtl::OUString::createFromAscii("office:document") );

// close document
xHandler->endDocument();


The first difficulty is with the instruction :
Code:

SvXMLAttributeList aAttrList;


Why ? Because when writing a C++ automation program we haven't the SvXMLAttributeList type defined. Then we have to write it. I have take the corresponding code from OOo source code :
<OOB680_m5>/filter/source/xsltdialog (attributelist.hxx and the corresponding attributelist.cxx) but because the reader could not have downloaded the corresponding code, I provide it completely here.
First we provide the corresponding class :
Code:

//Listing 10 AttributList class
// C++
struct AttributeList_Impl
{
   AttributeList_Impl()
   {
      // performance improvement during adding
      vecAttribute.reserve(20);
   }
   vector<struct TagAttribute_Impl> vecAttribute;
};

//  From  <OOB680_m5>/filter/source/xsltdialog/attributelist.hxx
class AttributeList : public WeakImplHelper1 < XAttributeList >
{
   AttributeList_Impl *m_pImpl;
public:
   AttributeList();
   virtual ~AttributeList();

   // methods that are not contained in any interface
   void AddAttribute( const OUString &sName , const OUString &sType , const OUString &sValue );
   void Clear();
   void RemoveAttribute( const OUString sName );
   void SetAttributeList( const Reference< XAttributeList > & );
   void AppendAttributeList( const Reference< XAttributeList > & );

   // ::com::sun::star::xml::sax::XAttributeList
   virtual sal_Int16 SAL_CALL getLength(void)
      throw( RuntimeException );
   virtual OUString SAL_CALL getNameByIndex(sal_Int16 i)
      throw( RuntimeException );
   virtual OUString SAL_CALL getTypeByIndex(sal_Int16 i)
      throw( RuntimeException );
   virtual OUString SAL_CALL getTypeByName(const OUString& aName)
      throw( RuntimeException );
   virtual OUString SAL_CALL getValueByIndex(sal_Int16 i)
      throw( RuntimeException );
   virtual OUString SAL_CALL getValueByName(const OUString& aName)
      throw( RuntimeException );

};

The complete implementation is :
Code:

//Listing 11 AttributList class Implementation
// C++
//*************** AttributeList impementation
// from    <OOB680_m5>/filter/source/xsltdialog/attributelist.hxx
sal_Int16 SAL_CALL AttributeList::getLength(void) throw( RuntimeException ){
   return m_pImpl->vecAttribute.size();
}

OUString SAL_CALL AttributeList::getNameByIndex(sal_Int16 i) throw( RuntimeException ){
   if( i < static_cast < sal_Int16 > (m_pImpl->vecAttribute.size()) ) {
      return m_pImpl->vecAttribute[i].sName;
   }
   return OUString();
}

OUString SAL_CALL AttributeList::getTypeByIndex(sal_Int16 i) throw( RuntimeException ){
   if( i < static_cast < sal_Int16 > (m_pImpl->vecAttribute.size() ) ) {
      return m_pImpl->vecAttribute[i].sType;
   }
   return OUString();
}

OUString SAL_CALL  AttributeList::getValueByIndex(sal_Int16 i) throw( RuntimeException ){
   if( i < static_cast < sal_Int16 > (m_pImpl->vecAttribute.size() ) ) {
      return m_pImpl->vecAttribute[i].sValue;
   }
   return OUString();
}

OUString SAL_CALL AttributeList::getTypeByName( const OUString& sName ) throw( RuntimeException ){
   vector<struct TagAttribute_Impl>::iterator ii = m_pImpl->vecAttribute.begin();

   for( ; ii != m_pImpl->vecAttribute.end() ; ii ++ ) {
      if( (*ii).sName == sName ) {
         return (*ii).sType;
      }
   }
   return OUString();
}

OUString SAL_CALL AttributeList::getValueByName(const OUString& sName) throw( RuntimeException ){
   vector<struct TagAttribute_Impl>::iterator ii = m_pImpl->vecAttribute.begin();

   for( ; ii != m_pImpl->vecAttribute.end() ; ii ++ ) {
      if( (*ii).sName == sName ) {
         return (*ii).sValue;
      }
   }
   return OUString();
}

AttributeList::AttributeList(){
   m_pImpl = new AttributeList_Impl;
}

AttributeList::~AttributeList(){
   delete m_pImpl;
}

void AttributeList::AddAttribute(const OUString &sName ,
                                 const OUString &sType ,
                                 const OUString &sValue ){
   m_pImpl->vecAttribute.push_back( TagAttribute_Impl( sName , sType , sValue ) );
}

void AttributeList::Clear(){
   m_pImpl->vecAttribute.clear();

   OSL_ENSURE( ! getLength(), "Length > 0 after AttributeList::Clear!");
}

void AttributeList::RemoveAttribute( const OUString sName ){
   vector<struct TagAttribute_Impl>::iterator ii = m_pImpl->vecAttribute.begin();

   for( ; ii != m_pImpl->vecAttribute.end() ; ii ++ ) {
      if( (*ii).sName == sName ) {
         m_pImpl->vecAttribute.erase( ii );
         break;
      }
   }
}

void AttributeList::SetAttributeList( const Reference< XAttributeList >  &r ){
   Clear();
   AppendAttributeList( r );
}

void AttributeList::AppendAttributeList( const Reference< XAttributeList >  &r ){
   OSL_ENSURE( r.is(), "r isn't!" );

   sal_Int32 nMax = r->getLength();
   sal_Int32 nTotalSize = m_pImpl->vecAttribute.size() + nMax;
   m_pImpl->vecAttribute.reserve( nTotalSize );

   for( sal_Int16 i = 0 ; i < nMax ; i ++ ) {
      m_pImpl->vecAttribute.push_back( TagAttribute_Impl(
         r->getNameByIndex( i ) ,
         r->getTypeByIndex( i ) ,
         r->getValueByIndex( i )));
   }
   OSL_ENSURE( nTotalSize == getLength(), "nTotalSize != getLength()");
}


To make a complete automation program, we have to provide a main program.
Code:

//Listing 12  The corrected Listing 9 program for automation.
// C++
int main( )
{
//retrieve an instance of the remote service manager
    Reference< XMultiServiceFactory > rOfficeServiceManager;
    rOfficeServiceManager = ooConnect();
    OSL_ENSURE(rOfficeServiceManager.is(), "Unable to connected to the office\n");
//get the desktop service using createInstance returns an XInterface type
    Reference< XInterface  > Desktop = rOfficeServiceManager->createInstance(
    OUString::createFromAscii( "com.sun.star.frame.Desktop" ));

//query for the XComponentLoader interface
    Reference< XComponentLoader > rComponentLoader (Desktop, UNO_QUERY);
    OSL_ENSURE(rComponentLoader.is() , "Unable to get XComponentloader service\n");
 
   Reference< XDesktop > rDesktop(Desktop,UNO_QUERY);
   OSL_ENSURE(rDesktop.is() , "Unable to get XDesktop service\n");
 
//get an instance of the OOowriter document
    Reference< XComponent > xWriterComponent = rComponentLoader->loadComponentFromURL(
   OUString::createFromAscii("private:factory/swriter"),
        OUString::createFromAscii("_blank"),
        0,
        Sequence < ::com::sun::star::beans::PropertyValue >());

// instantiate the XML import component
    OUString sService = OUString::createFromAscii("com.sun.star.comp.Writer.XMLImporter");
    Reference<XDocumentHandler> xImport(
         rOfficeServiceManager->createInstance(sService), UNO_QUERY );
    OSL_ENSURE( xImport.is(), "can't instantiate XML import" );

// ******** These important lines where not in the original listing
// I find the clue in <OOB680_m5>/filter/source/xmlfilteradaptor/XmlFilterAdaptor.cxx
// #include <com/sun/star/document/XImporter.hpp> added in this file
// using namespace com::sun::star::document; added in this file
// com.sun.star.document.XImporter \ added in the MakeFile
    Reference < XImporter > xImporter( xImport, UNO_QUERY );
    xImporter->setTargetDocument ( xWriterComponent );

// OK. Now we have the import. Let's make a real simple document.

// a few comments:
// 1. We will use string constants from xmloff/xmlkywd.hxx
// 2. For convenience, we'll use a globally shared attribute list from the
//    xmloff project (xmloff/attrlist.hxx)
// 3. In a real project, we would pre-construct our OUString, rather than use
//    the slow createFromAscii(\x{2026}) method every time.

// We will write the following document: (the unavoidable 'Hello World!')
// <office:document
//      office:class="text"
//      xmlns:office="http://openoffice.org/2000/office"
//      xmlns:text="http://openoffice.org/2000/text" >
//   <office:body>
//     <text:p>Hello World!</text:p>
//   </office:body>
// </office:document>
   

    xImport->startDocument();

//  SvXMLAttributeList aAttrList; in http://xml.openoffice.org/filter/
// It is possible to find the corresponding code in source :
//    <OOB680_m5>/filter/source/xsltdialog/attributelist.hxx and
//    <OOB680_m5>/filter/source/xsltdialog/attributelist.cxx
    AttributeList *xAttrList = new AttributeList();
    Reference< XAttributeList > aAttrList = static_cast< XAttributeList* > ( xAttrList );
   
// our first element: first build up the attribute list, then start the element
// DON'T FORGET TO ADD THE NAMESPACES!

xAttrList->AddAttribute(
    OUString::createFromAscii("xmlns:office"),
    OUString::createFromAscii("CDATA"),
    OUString::createFromAscii("http://openoffice.org/2000/office") );

xAttrList->AddAttribute(
    OUString::createFromAscii("xmlns:text"),
    OUString::createFromAscii("CDATA"),
    OUString::createFromAscii("http://openoffice.org/2000/text") );
xAttrList->AddAttribute(
    OUString::createFromAscii("office:class"),
    OUString::createFromAscii("CDATA"),
    OUString::createFromAscii("text") );

xImport->startElement(
    OUString::createFromAscii("office:document"),
    aAttrList );

// body element (no attributes)
aAttrList.clear();
xImport->startElement(
    OUString::createFromAscii("office:body"),
    aAttrList );

// paragraph element (no attributes)
aAttrList.clear();
xImport->startElement(
    OUString::createFromAscii("text:p"),
    aAttrList );

// write text
xImport->characters(
    OUString::createFromAscii("Hello World!") );

// close paragraph
xImport->endElement(
    OUString::createFromAscii("text:p") );

// close body
xImport->endElement(
    OUString::createFromAscii("office:body") );

// close document element
xImport->endElement(
    OUString::createFromAscii("office:document") );

// close document
xImport->endDocument();

  return 0;
}


Translating this code in OOoBasic (very easy to distribute) would be a very great thing : you could take every example from
OASIS OpenDocument Essentials[url]http://books.evc-cit.info/[/url] and put it with a button directly in a document (without file), through a dialog box for instance and see the result. It would be then the greater tool to learn OASIS XML (no perl, no file) and easy to use under Linux, Windows, MacOSX ....

But I am not sure the translation can be done (because of the attribute list) : can anybody help me ?
_________________
Linux & Windows OOo3.0
UNO & C++ : WIKI
http://wiki.services.openoffice.org/wiki/Using_Cpp_with_the_OOo_SDK
In French
http://wiki.services.openoffice.org/wiki/Documentation/FR/Cpp_Guide


Last edited by SergeM on Thu Aug 31, 2006 8:01 am; edited 1 time in total
Back to top
View user's profile Send private message Visit poster's website
ms777
Super User
Super User


Joined: 07 Feb 2004
Posts: 1355

PostPosted: Wed Aug 30, 2006 2:45 pm    Post subject: Re: Writing directly XML Instructions in a Document (C++, .. Reply with quote

SergeM wrote:
...
Translating this code in OOoBasic (very easy to distribute) would be a very great thing : you could take every example from
OASIS OpenDocument Essentialshttp://books.evc-cit.info/ and put it with a button directly in a document (without file), through a dialog box for instance and see the result. It would be then the greater tool to learn OASIS XML (no perl, no file) and easy to use under Linux, Windows, MacOSX ....

But I am not sure the translation can be done (because of the attribute list) : can anybody help me ?


There you are ... although I have to admit that I do not completely understand what it is good for Question

Have fun,

ms777

Code:
private Attr_nLength as integer
private Attr_Names() as String
private Attr_Types() as String
private Attr_Values() as String

Sub Main
  aAttrList = createUnoListener("ATTR_", "com.sun.star.xml.sax.XAttributeList")


  xWriterComponent = Stardesktop.loadComponentFromURL("private:factory/swriter","_blank", 0, Array())
  xImport = createUnoService("com.sun.star.comp.Writer.XMLImporter")
  xImport.setTargetDocument(xWriterComponent)

  xImport.startDocument()   
   
  ResetAttributeList
  AddAttribute("xmlns:office", "CDATA", "http://openoffice.org/2000/office")
  AddAttribute("xmlns:text", "CDATA", "http://openoffice.org/2000/text")
  AddAttribute("office:class", "CDATA", "text")


  xImport.startElement("office:document", aAttrList )

  ResetAttributeList
  xImport.startElement("office:body", aAttrList )

  ResetAttributeList
  xImport.startElement("text:p", aAttrList )

  xImport.characters("Hello World!")

  xImport.endElement("text:p")

  xImport.endElement("office:body")
  xImport.endElement("office:document")

  xImport.endDocument()

End Sub


sub ResetAttributeList
Attr_nLength = 0
end sub

sub AddAttribute(sName as String, sType as String, sValue as String)
Redim preserve Attr_Names(Attr_nLength)
Redim preserve Attr_Types(Attr_nLength)
Redim preserve Attr_Values(Attr_nLength)
Attr_Names(Attr_nLength) = sName
Attr_Types(Attr_nLength) = sType
Attr_Values(Attr_nLength)= sValue
Attr_nLength = Attr_nLength + 1
end sub





function ATTR_getLength() as integer
ATTR_getLength = Attr_nLength
end function

function ATTR_getNameByIndex( i as integer) as String
if i<0 then exit function
if i>ATTR_getLength then exit function
ATTR_getNameByIndex = Attr_Names(i)
end function

function ATTR_getTypeByIndex( i as integer) as String
if i<0 then exit function
if i>ATTR_getLength then exit function
ATTR_getTypeByIndex = Attr_Types(i)
end function

function ATTR_getTypeByName( aName as String) as String
for i=0 to ATTR_getLength-1
  if Attr_Names(i) = aName then
    ATTR_getTypeByName = Attr_Types(i)
    endif
  next i
end function

function ATTR_getValueByIndex( i as integer) as String
if i<0 then exit function
if i>ATTR_getLength then exit function
ATTR_getValueByIndex = Attr_Values(i)
end function

function ATTR_getValueByName( aName as String) as String
for i=0 to ATTR_getLength-1
  if Attr_Names(i) = aName then
    ATTR_getValueByName = Attr_Values(i)
    endif
  next i
end function
Back to top
View user's profile Send private message
SergeM
Super User
Super User


Joined: 09 Sep 2003
Posts: 3211
Location: Troyes France

PostPosted: Thu Aug 31, 2006 7:45 am    Post subject: Reply with quote

Quote:
There you are ... although I have to admit that I do not completely understand what it is good for

In the book : OASIS OpenDocument Essentials http://books.evc-cit.info/ J. David Eisenberg gives perl scripts to work around OASIS files and OpenOffice. I never check his examples because I am not a perl user. I was so happy to complete the code that I imagine quicly many things to do with this code, and as usualy speed is our enemy. I though I can have a text dialog where I write the XML text and then send it into OOo. But it is not so straightforward because of the attributes which require in fact that you parse the XML source : and in OOoBasic I cannot imagine for the moment to write such a parser.

I will however work around your code.
Thank you ms777
_________________
Linux & Windows OOo3.0
UNO & C++ : WIKI
http://wiki.services.openoffice.org/wiki/Using_Cpp_with_the_OOo_SDK
In French
http://wiki.services.openoffice.org/wiki/Documentation/FR/Cpp_Guide
Back to top
View user's profile Send private message Visit poster's website
SergeM
Super User
Super User


Joined: 09 Sep 2003
Posts: 3211
Location: Troyes France

PostPosted: Thu Aug 31, 2006 8:07 am    Post subject: Reply with quote

ms777,
I have tried your code which works exacly as my C++ code.
Your idea to use an event listener for "com.sun.star.xml.sax.XAttributeList" is probably something I would miss if I have tried to translate.
Translating so quick is incredible.
Have you already worked around such subject ?
_________________
Linux & Windows OOo3.0
UNO & C++ : WIKI
http://wiki.services.openoffice.org/wiki/Using_Cpp_with_the_OOo_SDK
In French
http://wiki.services.openoffice.org/wiki/Documentation/FR/Cpp_Guide
Back to top
View user's profile Send private message Visit poster's website
ms777
Super User
Super User


Joined: 07 Feb 2004
Posts: 1355

PostPosted: Thu Aug 31, 2006 12:24 pm    Post subject: Reply with quote

no - I never worked with XML. I made the abuse of createUnoListener some time ago ( http://www.oooforum.org/forum/viewtopic.phtml?t=17182 ), but I believe that I saw some earlier post afterwards. Unfortunately, createUnoListener takes only one interface, not more, and you cannot modify or add function definitions
Back to top
View user's profile Send private message
SergeM
Super User
Super User


Joined: 09 Sep 2003
Posts: 3211
Location: Troyes France

PostPosted: Fri Sep 01, 2006 10:52 am    Post subject: Reply with quote

You are impressive : to read so easy C++ and to program so easy OOoBasic !
I will try to go further with my idea in a little.
_________________
Linux & Windows OOo3.0
UNO & C++ : WIKI
http://wiki.services.openoffice.org/wiki/Using_Cpp_with_the_OOo_SDK
In French
http://wiki.services.openoffice.org/wiki/Documentation/FR/Cpp_Guide
Back to top
View user's profile Send private message Visit poster's website
SergeM
Super User
Super User


Joined: 09 Sep 2003
Posts: 3211
Location: Troyes France

PostPosted: Tue Sep 05, 2006 8:53 am    Post subject: Reply with quote

I give here one example using a SAX parser.
Have a look to
Using UNO's Xml sax parser via the API (DannyB) http://www.oooforum.org/forum/viewtopic.phtml?t=4907
where I take most of the code.
The example above take an XML file and send it into OOo for interpretation :

Code:

REM  *****  BASIC  *****

REM  **** Danny Brewer (Mon Jan 12, 2004) ****

DIM xImport As Object

Sub Main
  Dim Url as string, service as string
  Dim xComponent as object
  SUrl = "private:factory/swriter"
  service = "com.sun.star.comp.Writer.XMLImporter"
  xComponent = Stardesktop.loadComponentFromURL(SUrl,"_blank", 0, Array())
  xImport = createUnoService(Service)
  xImport.setTargetDocument(xComponent)
  InitSax
end sub
 
Sub InitSax
  cXmlFile = "/home/smoutou/demo1.xml" 
  cXmlUrl = ConvertToURL( cXmlFile )
  ReadXmlFromUrl( cXmlUrl )
End Sub

' This routine demonstrates how to use the Universal Content Broker's
' SimpleFileAccess to read from a local file.
Sub ReadXmlFromUrl( cUrl )
' The SimpleFileAccess service provides mechanisms to open, read, write files,
' as well as scan the directories of folders to see what they contain.
' The advantage of this over Basic's ugly file manipulation is that this
' technique works the same way in any programming language.
' Furthermore, the program could be running on one machine, while the SimpleFileAccess
' accesses files from the point of view of the machine running OOo, not the machine
' where, say a remote Java or Python program is running.
  oSimpleFileAccess = createUnoService( "com.sun.star.ucb.SimpleFileAccess" ) 
' Open input file.
  oInputStream = oSimpleFileAccess.openFileRead( cUrl )

  ReadXmlFromInputStream( oInputStream )
  oInputStream.closeInput()
End Sub

Sub ReadXmlFromInputStream( oInputStream )
' Create a Sax Xml parser.
  oSaxParser = createUnoService( "com.sun.star.xml.sax.Parser" )
' Create a document event handler object.
' As methods of this object are called, Basic arranges
' for global routines (see below) to be called.
  oDocEventsHandler = CreateDocumentHandler()
' Plug our event handler into the parser.
' As the parser reads an Xml document, it calls methods
' of the object, and hence global subroutines below
' to notify them of what it is seeing within the Xml document.
  oSaxParser.setDocumentHandler( oDocEventsHandler )
' Create an InputSource structure.
  oInputSource = createUnoStruct( "com.sun.star.xml.sax.InputSource" )
  With oInputSource
    .aInputStream = oInputStream ' plug in the input stream
  End With
' Now parse the document.
' This reads in the entire document.
' Methods of the oDocEventsHandler object are called as
' the document is scanned.
  oSaxParser.parseStream( oInputSource )
End Sub

'==================================================
'  Xml Sax document handler.
'==================================================
' Global variables used by our document handler.
'
' Once the Sax parser has given us a document locator,
' the glLocatorSet variable is set to True,
' and the goLocator contains the locator object.
'
' The methods of the locator object has cool methods
' which can tell you where within the current Xml document
' being parsed that the current Sax event occured.
' The locator object implements com.sun.star.xml.sax.XLocator.
'
Private goLocator As Object
Private glLocatorSet As Boolean

' This creates an object which implements the interface
' com.sun.star.xml.sax.XDocumentHandler.
' The doucment handler is returned as the function result.
Function CreateDocumentHandler()
' Use the CreateUnoListener function of Basic.
' Basic creates and returns an object that implements a particular interface.
' When methods of that object are called,
' Basic will call global Basic functions whose names are the same
' as the methods, but prefixed with a certian prefix.
  oDocHandler = CreateUnoListener( "DocHandler_", "com.sun.star.xml.sax.XDocumentHandler" )
  glLocatorSet = False
  CreateDocumentHandler() = oDocHandler
End Function

'==================================================
'  Methods of our document handler call these
'  global functions.
'  These methods look strangely similar to
'  a SAX event handler. ;-)
'  These global routines are called by the Sax parser
'  as it reads in an XML document.
'  These subroutines must be named with a prefix that is
'  followed by the event name of the com.sun.star.xml.sax.XDocumentHandler interface.
'==================================================
Sub DocHandler_startDocument()
  'Print "Start document"
  xImport.startDocument()
End Sub

Sub DocHandler_endDocument()
' Print "End document"
  xImport.endDocument()
End Sub

Sub DocHandler_startElement( cName As String, oAttributes As com.sun.star.xml.sax.XAttributeList )
  'Print "Start element", cName
  xImport.startElement(cName, oAttributes ) 
End Sub

Sub DocHandler_endElement( cName As String )
'  Print "End element", cName
   xImport.endElement(cName)
End Sub

Sub DocHandler_characters( cChars As String )
   xImport.characters(cChars ) 
End Sub

Sub DocHandler_ignorableWhitespace( cWhitespace As String )
End Sub

Sub DocHandler_processingInstruction( cTarget As String, cData As String )
End Sub

Sub DocHandler_setDocumentLocator( oLocator As com.sun.star.xml.sax.XLocator )
' Save the locator object in a global variable.
' The locator object has valuable methods that we can
' call to determine
  goLocator = oLocator
  glLocatorSet = True
End Sub


The content of the "/home/smoutou/demo1.xml" file could be for instance :
Code:

<office:document
      office:class="text"
      xmlns:office="http://openoffice.org/2000/office"
      xmlns:text="http://openoffice.org/2000/text" >
<office:body>
  <text:p>
    Hello World!
  </text:p>
</office:body>
</office:document>

_________________
Linux & Windows OOo3.0
UNO & C++ : WIKI
http://wiki.services.openoffice.org/wiki/Using_Cpp_with_the_OOo_SDK
In French
http://wiki.services.openoffice.org/wiki/Documentation/FR/Cpp_Guide
Back to top
View user's profile Send private message Visit poster's website
Display posts from previous:   
Post new topic   Reply to topic    OOoForum.org Forum Index -> OpenOffice.org Code Snippets All times are GMT - 8 Hours
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2005 phpBB Group