Lodahl's blog: XML
Showing posts with label XML. Show all posts
Showing posts with label XML. Show all posts

03 December 2013

LibreOffice now has a built in XML-parser

LibreOffice is using a XML based document format so of cause there is a built in XML parser. But until now it has been quite cumbersome to deal with XML in macros. You need to manually traverse through the entire XML structure like this example (thanks to Andrew Pitonyak):

Function CreateDocumentHandler()
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_characters( cChars As String )

if xNode = "lipsum" then
oWrite=1
cChars= Left(cChars,len(cChars)-1)
if len(cChars)>1 then
cChars= cChars+ Chr$(13)
else
cChars=cChars
endif
WriteLoremipsum (cChars, oWrite)
Else oWrite=0
Endif
End Sub

Sub DocHandler_ignorableWhitespace( cWhitespace As String )
End Sub

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

Sub DocHandler_startDocument()
End Sub

Sub DocHandler_endDocument()
End Sub

Sub DocHandler_startElement( cName As String, oAttributes As com.sun.star.xml.sax.XAttributeList )
xNode = cName
End Sub

Sub DocHandler_endElement( cName 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

This example above is from the extension Lorem Ipsum generator that you can download from here: http://extensions.libreoffice.org/extension-center/magenta-lorem-ipsum-generator

But now its much easier as LibreOffice 4.2 comes with two new spreadsheet functions called WEBSERVICE and FILTERXML. In a macro it is possible to call and use such built in spreadsheet functions even when you are working with text documents.

The example below does pretty much the same as the one above

Sub Main
svc = createUnoService( "com.sun.star.sheet.FunctionAccess" ) 'Create a service to use Calc functions
XML_String = svc.callFunction("WEBSERVICE",array("http://www.lipsum.com/feed/xml?amount=2&what=paras&start=Yes"))
Lipsum = svc.callFunction("FILTERXML", array(XML_String, "/feed/lipsum" ))
Print Lipsum
End Sub

I'm really looking forward play around with these nifty little features in Calc.

26 September 2009

Extension help content

I have created a few extensions over the last few years. Some of them even include help content to help the users. One problem is, that the XML syntax are rather dificult to figure out. Even a simple document with a few headers and some paragraphs are rather difficult to create.

It would be rather nice if there where an export filter for xhp-files. I have head that such filter exists but I have never found it.

Expired by this article an Linux Magazine by Dimtri Popov ( http://www.linux-magazine.com/Online/Blogs/Productivity-Sauce-Dmitri-s-open-source-blend-of-productive-computing/Format-Writer-Documents-with-Any-Markup ) I decided to try to make a macro to export a document to xhp. So far I got headers, paragraphs and links. There is still some work to do because tables and pictures.

Also the macro will mess up the original document. It would be nice if it only exported the content leaving the original text untouched.

Here is the macro:


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

Sub HelpContent
If not ThisComponent.hasLocation Then
MsgBox ("Save document befor export", 0 ,"Export to Help content")
stop
End If


MarkupHeadingsFunc("Text body", "", "")
MarkupHeadingsFunc("Heading 1", "", "")
MarkupHeadingsFunc("Heading 2", "", "")
MarkupHeadingsFunc("Heading 3", "", "")
MarkupTextFunc("CharWeight", com.sun.star.awt.FontWeight.BOLD, "&")
MarkupURLFunc

AddText
ExportTheThing

End Sub

Function MarkupHeadingsFunc (StyleName, StartTag, EndTag)
ThisDoc=ThisComponent
ThisText=ThisDoc.Text
ParaEnum=ThisText.createEnumeration
While ParaEnum.hasmoreElements
Para=ParaEnum.nextElement
PortionEnum = Para.createEnumeration
While PortionEnum.hasMoreElements
Portion=PortionEnum.nextElement
If Portion.paraStyleName = StyleName then
Portion.String = StartTag + Portion.String + EndTag
End if
Wend
Wend
End Function

Function MarkupTextFunc(SearchAttrName, SearchAttrValue, ReplaceStr)
Dim SearchAttributes(0) As New com.sun.star.beans.PropertyValue
ThisDoc=ThisComponent
SearchAttributes(0).Name=SearchAttrName
SearchAttributes(0).Value=SearchAttrValue
ReplaceObj=ThisDoc.createReplaceDescriptor
ReplaceObj.SearchRegularExpression=true
ReplaceObj.searchStyles=false
ReplaceObj.searchAll=true
ReplaceObj.SetSearchAttributes(SearchAttributes)
ReplaceObj.SearchString=".*"
ReplaceObj.ReplaceString=ReplaceStr
ThisDoc.replaceAll(ReplaceObj)
End Function

Sub MarkupURLFunc
ThisDoc=ThisComponent
ThisText=ThisDoc.Text
ParaEnum=ThisText.createEnumeration
While ParaEnum.hasmoreElements
Para=ParaEnum.nextElement
PortionEnum=Para.createEnumeration
While PortionEnum.hasMoreElements
Portion=PortionEnum.nextElement
If Portion.HyperlinkURL <> "" then
Portion.String = "" +Portion.String + ""
End if
Wend
Wend
End Sub

function SetFileName() as String


Dim oDoc
Dim sDocURL
If (Not GlobalScope.BasicLibraries.isLibraryLoaded("Tools")) Then
GlobalScope.BasicLibraries.LoadLibrary("Tools")
End If

sDocURL = ThisComponent.getURL()
Directory = DirectoryNameoutofPath(sDocURL, "/")
File_Name = FileNameoutofPath(sDocURL, "/")
New_File_name = ConvertFromUrl(Left(File_Name, Len(File_Name)-4))


SetFileName = ""
boInitialized = false

oListener = CreateUnoListener("MyPick01_", "com.sun.star.ui.dialogs.XFilePickerListener")
oFP = CreateUnoService( "com.sun.star.ui.dialogs.FilePicker" )
With oFP
.setMultiSelectionMode(False)

.Initialize( Array(com.sun.star.ui.dialogs.TemplateDescription.FILESAVE_SIMPLE) )
.appendFilter("Help content", "*.xhp" )
.setTitle( "Help content ..." )
.setDisplayDirectory(Directory)
.setDefaultName(New_File_Name & ".xhp")



If .execute() Then OpenFile = .Files(0)

.removeFilePickerListener(oListener)
.Dispose()
End With
SetFileName = OpenFile

If SetFileName = "" Then
Stop
End if


end function

sub AddText


Starttext= "" & CHR$(10) & "" & CHR$(10) & "" & CHR$(10) & "" & CHR$(10) & "write title here" & CHR$(10) & "write filename here" & CHR$(10) & "" & CHR$(10) & "" & CHR$(10) & "" & CHR$(10) & "" & CHR$(10) & "xxx" & CHR$(10) & "xxx; yyy" & CHR$(10) & ""

EndText = CHR$(10) & "" & CHR$(10) & "
"

Dim oText As Object
oText = ThisComponent.Text

REM Insert some simple text at the start
oText.insertString(oText.getStart(), StartText & CHR$(13), False)
REM Append a new paragraph at the end
oText.insertString(oText.getEnd(), EndText & CHR$(13), False)



end sub

sub ExportTheThing
FileName = SetFilename()


Dim args(0) as new com.sun.star.beans.PropertyValue
args(0).Name = "FilterName"
args(0).Value = "Text"
ThisComponent.storeToURL(FileName,args())


end sub

REM ***** END BASIC *****

10 September 2009

Export from OpenOffice to Freemind

I just launched a new extension that exports the structure of headings in a text document to Freemind 0.8 format.




Quite nice if you need to get an overview of a large document.

Please help me test it.

http://extensions.services.openoffice.org/project/Freemind

15 January 2008

OpenProj 1.0 is now available

In August last year the company Projity (http://www.projity.com/) announced the second beta version of the desktop application OpenProj (http://www.openproj.org). Today Projity released the first 'real' version of the same application.

It is very nice to see a serious competitor to Microsoft Projects and I am looking forward to look closer to the details in the application functionality one of the comming days. According to the website I can expect to find Gantt Charts, Network Diagrams (PERT Charts), WBS and RBS charts, Earned Value costing and even more.

For now I will just note a few details:
The application is open source, and this is of cause positive, because it gives us users the safty we need, because we can download the source code and find how the file format is designed. But the application uses a binary fileformat (.pod) for storing the project information. It is possible to export the project information in Microsoft Project 2003 (XML) file format. It would be nice if the native file format was xml based and perhaps based on some kind of standard file format.

The application is based on Java code and is not depending on a single software platform or operating system. It has been released for Linux, Unix, Mac and Windows.

The open source license is a so called Common Public Attribution License Version 1.0 (CPAL) witch is approved by OSI https://www.eu.socialtext.net/open/index.cgi?cpal.

All together I find this initiative very nice, but I don't think this is the great revolution for now. If the company can establish a solid user community that can take some of the mising details, I think this could grow over time. I would like some more user documentation and mayby a few example projects to download.

12 December 2007

Groklaw: Denmark Pretends MSOOXML is an "Open Standard"

According to Grocklaw the Danish government is pretending that EOOXML is an open standard approved by ISO. http://www.groklaw.net/article.php?story=20071211153924324

It's true that the public authorities is about to implement open standards in the public sector and that EOOXML is one of the accepted standards.

It must be emphasized that the ISO approval (or rejection) has never been a part of the discussion in the Danish Parliament. The ISO approval is not the final and true prove weather a document format is an open standard. ISO doesn't have the final word, but the the decision will of cause have effects in Denmark as well.

The Danish decision is this:

  • ODF is an open standard (accepted)
  • EOOXML is for now accepted as an open standard, but Microsoft must prove true openness in the process before end of 2008. The Danish Competition Authority has been asked to look after this.
I have talked to a few MP's about this both last summer when the discussion was open in the Parliament but also this late autumn where there was an election for Parliament. The politicians is very much aware of this problem and Microsoft will not get a final accept if the process isn't getting more open.

03 October 2007

Extending OpenOffice.org

Sorry, I have been away from my blog for a few days.

This summer I wrote a Danish manual about extensions and how to create and maintain extensions( http://doc.oooforum.dk/Extensions.pdf ). When I wrote the manual, I used both the wiki on http://www.OpenOffice.org : http://wiki.services.openoffice.org/wiki/Extensions . I also used two articles by Dimitri Popov (http://www.linuxjournal.com/article/7802 and http://www.linuxjournal.com/article/9412).

Dimitri is using an example in his article, where he is creating dummy text with Lorem Ipsum. I remember, that it was annoying that the example was masde as a mock up as example and didn't actually create Lorem Ipsum text. I know that this was not the purpose of the article, but I was still thinking: "Why not do it ?".

I have never made a macro in OpenOffice.org before, so I took this as a challenge. I had to find out everything from the beginning and I has some difficulties extracting data from the XML stream. The solution is a little clumsy, I will admit that. If any of you know a better and more elegant way, please feel free to make a new macro.

There is still a few other issues , but I expect to get them solved over the next few weeks.

I have uploaded the solution as extension to the repository, but it's actually not published yet. You can find the odt-file here: http://extensions.services.openoffice.org/download/288

When you have installed the extension, you will see a new tool bar with a button. This button will call http://www.lipsum.com/ give you some dummy text. Not rocket science, but anyway a helpfull feature.

Thanks to DannyB for this description of how to parse an XML stream http://www.oooforum.org/forum/viewtopic.phtml?t=4907 and to Andrew Pitonyak for his dokumentation "Useful Macro Information".