Trying to parse a file with SAX
Hi All,
I have some code which takes a XML DTD and parses it, writing information to System.out. Or it's meant to - I cannot get the parser to see the DTD file.
The code is:
public static void main (String[] args)
try
Class loadedClass = Class.forName("com.ibm.xml.parser.SAXDriver");
Parser xParser = (Parser)loadedClass.newInstance();
CatalogueReader cr = new CatalogueReader();
xParser.setDocumentHandler(cr);
xParser.setErrorHandler(cr);
xParser.parse("catalogue1.txt");
catch(Exception e)
{System.out.println("Problem: " +e.getMessage());}
which produces the following message:
Problem: catalogue1.txt (The system cannot find the file specified)
I have added the text file to the project and tried putting it in various folders without success.
I've been stuuck on this for a day now and would appreciate a nudge in the right direction.
Many thanks.
You might try creating a separate class and putting all your code in that class's constructor and seeing if that works. (have main() instansiate that class in order to run the code). I try to avoid putting code that parses directly in main(). You can also add the following to your main() and / or class's constructor to see what directory its is running from:
File file=new File("");
System.out.println(file.getAbsolutePath());
Lets say your catalogue1.txt file is two directories 'up' from the path given from getAbsolutePath() above, and one level down in a package called 'books', then this
might work:
xParser.parse("../../books/catalogue1.txt");
or
xParser.parse("././books/catalogue1.txt");
Similar Messages
-
Every time I am trying to open Quicktime files with my Quicktime it wants to convert the files. Why?
QuickTime version 10.3 will "convert" older legacy codecs into a more modern version. You can save this newer version and delete the older one.
This can only mean that support for those codecs will be removed completely some time in the future. -
How to Create XML file with SAX parser instead of DOM parser
HI ALL,
I am in need of creating an XML file by SAX parser ONLY. As far as my knowledge goes, we can use DOM for such purpose(by using createElement, creatAttribute ...). Can anyone tell me, is there any way to create an XML file using SAX Parser only. I mean, I just want to know whether SAX provides any sort of api for Creatign an element, attribute etc. I know that SAX is for event based parsing. But my requirement is to create an XML file from using only SAX parser.
Any help would be appreciated
Thanx in advance
KaushikHi,
You must write a XMLWriter class yourself, and that Class extends DefaultHandle ....., the overwrite the startElement(url, localName, qName, attributeList), startDocument(), endElement().....and so on.
in startElement write your own logic about how to create a new element and how to create a Attribute list
in startDocument write your own logic about how to build a document and encodeType, dtd....
By using:
XMLWriter out = new XMLWriter()
out.startDocument();
Attribute attr1 = new Atribute();
attr1.add("name", "value");
out.startElement("","","Element1", attr1);
Attribute attr2 = new Atribute();
attr2.add("name", "value");
out.startElement("","","Element2", attr2);
out.endElement("","","Element2");
out.endElement("","","Element1");
out.endDocument(); -
Reading xml file with sax parser: unknown protocol: c
Hi,
I've been googling around, and the best I can find is that the file name:
File test = new File("lib/test/parseTest/validate-test.xml");should be a url:
File test = new File("File://lib/test/parseTest/validate-test.xml");but I'm working on a linux machine and can't put "File://c:/pathToFile/file.xml"
Also, I did some testing and I can read a small xml file with just a few elements, but on large complex files, I get that error.
anyone ever run into this before?
bp
Edited by: badperson on Nov 1, 2008 2:19 PMbadperson wrote:
I've been googling around, and the best I can find is that the file name:
File test = new File("lib/test/parseTest/validate-test.xml");should be a url:
File test = new File("File://lib/test/parseTest/validate-test.xml");
No, that's wrong. The parameter for that constructor is a file path (relative or absolute). Not a URL. You must have misunderstood whatever you read.
but I'm working on a linux machine and can't put "File://c:/pathToFile/file.xml"What kind of a Linux machine is this which has a C drive? You must have misunderstood whoever told you to do that. -
Dear all, I am so confused�.
I have been trying for the last few days to understand how sax works� The only thing I understood is:
DefaultHandler handler = new Echo01();
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
out = new OutputStreamWriter(System.out, "UTF8");
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(file , handler);
} catch (Throwable t) {
t.printStackTrace();
System.exit(0);
}Ok, I assign the SAXParser the xml file and a handler. The parser parses and throws events that the handler catches. By implementing some handler interface or overriding the methods of an existing handler (e.g DeafultHandler class) I get to do stuff�
But still, suppose I have implement startElement() method of DefaultHandler class and I know that the pointer is currently placed on an element e.g. <name>bob</name>. How do I get the value of the element, and if I manage to do that, how can I replace�bob� with �tom�?
I would really appreciate any help given� just don�t recommend http://java.sun.com/webservices/jaxp/dist/1.1/docs/tutorial/ because although there are interesting staff in there, it does not solve my problem�Maybe SAX is not the right tool for you.
With SAX, you implement methods like startElement and characters that get called as XML data is encountered by the parser. If you want to catch it or not, the SAX parser does not care. In your case, the "bob" part will be passed in one or more calls to characters. To safely process the data, you need to do something like build a StringBuffer or StringBuilder in the constructor of the class, and then in the startElement, if the name is one you want to read, set the length to zero. In the characters method, append the data to the StringBuilder or StringBuffer. In the endElement, do a toString to keep the data wherever you want.
This works for simple XML, but may need to be enhanced if you have nested elements with string values that contain other elements.
On the other hand, if your file is not huge, you could use DOM. With DOM, (or with JDOM, and I would expect with Dom4J -- but I have only used the first two) you do a parse and get a Document object with the entire tree. That allows you to easily (at least it is easy once you figure out how to do it) find a node like the "name" element and change the Text object that is its child from a value of "bob" to "tom". With DOM, you can then serialize the modified Document tree and save it as an XML file. SAX does not have any way to save your data. That burden falls to you entirely.
Dave Patterson -
How to parse XML file with namesapce?
Hi,
I am trying to parse an xml file having namespace. But no data is returned.
Sample Code:
public class XMLFileLoader
var xml:XML = new XML();
var myXML:XML = new XML();
var XML_URL:String = "file:///C:/Documents and Settings/Administrator/Desktop/MyData.xml";
var myLoader:URLLoader = null;
public function XMLFileLoader()
var myXMLURL:URLRequest = new URLRequest(XML_URL);
myLoader= new URLLoader(myXMLURL);
myLoader.addEventListener(Event.COMPLETE,download);
public function download(event:Event):void
myXML = XML(myLoader.data);
var ns:Namespace=myXML.namespace("xsi");
for(var prop:String in myXML)
trace(prop);
//Alert.show(myXML..Parameters);
//trace("Data loadedww."+myXML.toString());
//Alert.show(myXML.DocumentInfo.attributes()+"test","Message");
The XML Contains the following format.
<Network xmlns="http://www.test.com/2005/test/omc/conf"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.test.com/2005/test/omc/conf/TestConfigurationEdition3proposal4.xsd">
<TestDomain>
<WAC>
<!--Release Parameter -->
<Parameters ParameterName="ne_release" OutageType="None"
accessRight="CreateOnly" isMandatory="true"
Planned="false"
Reference="true" Working="true">
<DataType>
<StringType/>
</DataType>
<GUIInfo graphicalName="Release"
tabName="All"
description="Describes the release version of the managed object"/>
</Parameters>
</TestDomain>
</Network>
Any sample code how to parse this kind of xml file with namespaces...
Regards,
Purushothami have exactly the same problem with KXml2, but using a j2me-polish netbeans project.
i've tried to work around with similar ways like you, but none of them worked. now i've spent 3 days for solving this problem, i'm a bit disappointed :( what is wrong with setting the downloaded kxml2 jar path in libraries&resources?
screenshot -
Parse xml file with validating againat dtd
i have a xlm file looks like:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE map SYSTEM "map.dtd">
<map width="20" height="15" goal="25" name="eXtreme Labyrinth of Dooom">
<random-item type='lantern' amount='5' />
<random-item type='health' amount='10' />
<tile x="14" y="0" type="wall">
<renderhint>wall:rock,cracked</renderhint>
</tile>
<tile x="15" y="0" type="wall" />
<tile x="16" y="0" type="floor">
<renderhint>floor:marble,cracked</renderhint>
</tile>
<tile x="17" y="0" type="floor">
<renderhint>floor:stone,rubble</renderhint>
</tile>
<tile x="18" y="0" type="floor" />
<tile x="0" y="1" type="floor" />
<tile x="1" y="1" type="floor" startlocation="1" />
<tile x="2" y="1" type="floor" />
<tile x="3" y="1" type="floor">
<item type="treasure">Bar of Silver</item>
<renderhint>floor:stone,blood</renderhint>
</tile>
<tile x="4" y="1" type="wall" />
<tile x="5" y="1" type="wall" />
<tile x="6" y="1" type="wall">
<renderhint>wall:bricks,cracked</renderhint>
</tile>
</map>and a dtd document like:
<!ELEMENT map (random-item+, tile+)>
<!ATTLIST map
width CDATA #REQUIRED
height CDATA #REQUIRED
goal CDATA #REQUIRED
name CDATA #REQUIRED
<!ELEMENT random-item EMPTY>
<!ATTLIST random-item
type (armour|health|sword|treasure|lantern) #REQUIRED
amount CDATA #REQUIRED
<!ELEMENT tile (item|renderhint)*>
<!ATTLIST tile
x CDATA #REQUIRED
y CDATA #REQUIRED
type (exit|floor|wall) #REQUIRED
startlocation CDATA #IMPLIED
<!ELEMENT item (#PCDATA)>
<!ATTLIST item
type (armour|health|sword|treasure|lantern) #REQUIRED
<!ELEMENT renderhint (#PCDATA)>i need to validate the xml file against the dtd document and parse it to java using DOM.
Can anyone give ma any suggestions on how to do it?
thank youi have started my coding like:
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import java.io.*;
class loadxml
public static void main(String[] args)
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setIgnoringElementContentWhitespace(true);
DocumentBuilder parser = factory.newDocumentBuilder();
Document doc = parser.parse(new File("hallways.xml"));
loadxml load = new loadxml();
load.parseNode(doc);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
public void parseNode (Node node) throws IOException
// here is where i have problem with
}since in my xml file, i have got ATTLIST, this ready confuses me when i try to coding it.
Can anyone help me, please.
Thank you.
Edited by: mujingyue on Mar 12, 2008 3:10 PM -
Correct way to parse the file with named captures
Hello!
I'm trying to build the configuration parser script, as I'm new on powershel /regex I have a lot of questions.
I have the following source file:
add chain=input comment=Accept dst-port=53 protocol=udp src-address-list=DNS_servers
add chain=input comment=AcceptDNSqueries dst-port=53 protocol=udp src-address-list=Servers
add chain=input comment=AcceptDNS dst-port=53 protocol=tcp src-address-list=DNS_servers
add chain=input comment=DHCP_relay dst-address-list=DHCP dst-port=67,68 protocol=udp src-address-list=IntIp
The following result should be done (results as csv format, the captures with no value are divided by seperator):
Chain,Comment,dst-port,protocol,src-address-list,dst-address-list
input,Accept,53,udp,DNS_servers,,
input,AcceptDNSqueries,53,udp,,Servers
input,Acceptudp,,udp,,Servers
According the following
link we can use the named captures. I have played with it and noticed that this script works only when data is at predefined order (or by using a lot of or expressions by repeating them when needed).
Question: how to parse the file when it's possible to use various captures with data located on different order(some values at configuration file is missing)? Is it possible to modify the script on link or we need to work with different approach?
Thanks!Try this:
$text =
add chain=input comment=Accept dst-port=53 protocol=udp src-address-list=DNS_servers
add chain=input comment=AcceptDNSqueries dst-port=53 protocol=udp src-address-list=Servers
add chain=input comment=AcceptDNS dst-port=53 protocol=tcp src-address-list=DNS_servers
add chain=input comment=DHCP_relay dst-address-list=DHCP dst-port=67,68 protocol=udp src-address-list=IntI
'@ | set-content sourcefile.txt
get-content sourcefile.txt |
foreach {
new-object PSObject -Property $($_ -replace '^add ' -replace ' ',"`n" | convertfrom-stringdata) |
select Chain,Comment,dst-port,protocol,src-address-list,dst-address-list
} | ft -auto
chain comment dst-port protocol src-address-list dst-address-list
input Accept 53 udp DNS_servers
input AcceptDNSqueries 53 udp Servers
input AcceptDNS 53 tcp DNS_servers
input DHCP_relay 67,68 udp IntI DHCP
I know, it's not "named captures", but those key=value pairs just beg to be run through convertfrom-stringdata.
Edit: just noticed I missed the dst-address-list. Fixed.
[string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " " -
Parsing XML file with different languages (Xerces)
How do we code or program to an XML file with different
languages , say english and spanish. WHen we parse such a document with the default locale , the presence of special characters throws errors .For eg when I use xerces and use
DOMParser parser = new DOMParser();
try
// Parse the XML Document
parser.parse(xmlFile);
catch (SAXException se)
se.printStackTrace();
org.xml.sax.SAXParseException: An invalid XML character (Unicode: 0xfc) was found in the element content of the document.
System Error: void org.apache.xerces.framework.XMLParser.parse(org.xml.sax.InputSource)
So what locale do we set before we parse ?How to handle this problemYou need an encoding attribute in the xml declaration. If you don't, the parser assumes UTF-8, which are ASCII characters up to 127 - useful (only) for English.
So, something like this would allow you to use characters above 127, ISO-8859-1 is the encoding used by standard PCs.
<?xml version="1.0" encoding="ISO-8859-1"?>
You can find a (offical) list of encodings at:
http://www.iana.org/assignments/character-sets
I'm not sure about mixing various encodings. I think you have to resort external parsed entities, which can have their own encoding, but I think you cannot mix encodings in one XML file.
Good luck. -
Error when trying to open Mac file with Captivate 6 Win
I've tried opening Captivate 6 files (.cptx/.cptl) that were created on the Mac version with Captivate 6 on Win7. Got the error message "can't open file" telling me to check the file and my resources. Resources are ok, the file was sent via email.
How can I set up a workflow for Captivate 6 between Mac and PC users that works? The discussion to Win files crashing Captivate Mac didn't help as there's no solution posted. Are there any issues concerning the compatibility of Mac and Win files within Captivate 6?
Any help is very much appreciated a we've got a deadline looming.
Regards,
SusanneSame problem here. Something to do with path to
swfobject_modified.js??
Even though I have correct path I still can't get it to work
on CMS site, even though it works OK on static site:
www.askew.co.nz (SWF is a red ellipse with mirrored "S")
The problem page (CMS site) is here:
http://askew-site.fjstaging01.pbstaging.com/
The error is:
<!--
swfobject.registerObject("FlashID");
//-->
(line 144 Uncaught ReferenceError: swfobject is not
defined) -
Trying to download xls file with IE7 but browser tries to download as htm
Hi!
I have got a problem with downloading files using a hyperlink.
I've got a hyperlink and i did set the url property to: /resources/file.xls
when using IE7 and clicking Save As... the save as dialog appears and suggests file.htm as the filename and the file typ is shown as: HTML Document
Firefox works fine, it suggests file.xls and the type as: Microsoft Office Excel 97-2003 Worksheet
Next i typed in the url of the resource folder: http://localhost:29080/myProject/resources/
The file was shown as file.xls in the directoy listing, but when i tried to download the file from here, both browsers behaved the same way as before.
gif-files and others worked fine in both browsers.
Does anyone have an idea?
greets,
RemiI'd first try downloading an installer from the Apple website using a different web browser:
http://www.apple.com/itunes/download/
If you use Firefox instead of IE for the download (or vice versa), do you get a working installer? -
Parsing a file with different groupings!
I need to parse a file. The file looks like this.
ABC45 CLIENT-90 MY COMPANY-0333 STOCK VS POSITIONS DATE
......n number of records here
ABC45 CLIENT-90 MY COMPANY-0897 STOCK VS POSITIONS DATE
.....n number of records here
ABC 45 CLIENT-90 MY COMPANY-0333 STOCK VS POSITIONS DATE
....n number of records here
ABC 45 CLIENT-90 MY COMPANY-0367 STOCK VS POSITIONS DATE
....n number of records hereI need to get all the records under say "MY COMPANY-0333" and parse them further and output to a text file. How can I do that?
ThanksYou have header and detail records, I suppose. Let's call them that. Pseudocode:boolean rightStuff = false;
for each record:
if it's a header record:
if it has MY COMPANY-0333 in the right place then rightStuff = true else rightStuff = false
if it's a detail record:
if rightStuff then process it and write to the filePC² -
Can someone please tell me how I can convert video files with an extension of IDI_DVD to a file itunes and imovie can read? Thanks.
Thanks for the reply, The files are on a DVD disk. I coverted my family VHS tapes to digital dvds using an HP Media Centre PC five or more years ago cant remember the program but if I get info on the disk ,on the Mac it tells me the extension is IDI_DVD.
-
Anyone tried using a QText file with FCP?
I was just wondering if there is some way to utilize a QText file for captioning with FCP, either directly of by importing it into QTPro, then exporting it in a form that FCP understands? The idea is to use these as timed text overlays.
QText is a bit more, at least to my limited understanding. Let's say you have a QText file with 10 lines of text you want to display. In the header you can specify color, size, etc. Before each line of text you enter a time code which represents the start time for displaying that line. For example:
[00:00:00]
This is my first line and displays for 4 seconds
[00:00:04]
This line is displayed 4 seconds after the first, and displays for 6 seconds
[00:00:10]
and this line is 6 seconds after the one above (i.e. 10 seconds in).
and so on. One way to look at it, each line of text becomes a slide which displays until the next line is called.
When fed to QTime, you get a very nice vector graphics display of each line at the specified time. It would be great if I could export that as a video file which I then could use in an overlay track in FCP. QTPro offers several export options including such as MP4, m4v, etc. Dragging these files into FCP either generates a Codec error when rendered or isn't recognized at all. I guess I could use a video screen capture program and capture the QTP display, but that seems like a crude and slow process. I had hoped, since FCP and QTP are both Apple products they would have found some way to integrate them. No mention of QText in the FCP help file, so it would appear no such luck. -
Trying to delete multiple files with very basic VBS script
Good day,
I've found a script and modified it for an input box to accommodate multiple files being deleted but I'm not sure if it is capable or if I'm just using the wrong syntax within the input box:
Script:
Set obj = CreateObject("Scripting.FileSystemObject") 'Calls the File System Object
obj.DeleteFile inputbox("Enter files and path to be deleted") 'Deletes the file throught the DeleteFile function
When prompted and I put just one file path to the file I want deleted it works, but if I put in multiple files and their paths either separated by colan, semi colan or space, it says "bad file path or number". If anyone knows of a VBS
or powershell script that references a text file or .csv spreadsheet that would be sooper handy!
Many thanks - RP
bertoThank you Bill!
Sounds like I need a different method all together. I found this script that references a .csv file with the folder paths and file names; does it seem legit to you guys? Also for files that are past the 256 UNC character length, is there a work
around for that?
12
$files = Get-Content "C:\scripts\delete-files.csv"
13
14
foreach ($file in $files) {
15
Remove-Item -Path
$file -force
16
17
18
write-host -foregroundcolor yellow "Delete action complete"
berto
Try this to see:
$files = Get-Content "C:\scripts\delete-files.csv"
foreach ($file in $files) {
Remove-Item -Path $file -force -WhatIf
write-host -foregroundcolor yellow "Delete action complete"
¯\_(ツ)_/¯
Maybe you are looking for
-
Boot camp and Vista...Windows give me boot up error
I have the macbookpro with os 10.5.6. I just installed windows vista ultimate on bootcamp and loaded all the drivers. Everything works well except that when I boot up windows, in the beginning it gives me something like this: Unrecognized partition,
-
Hot back of iphone 4 when charging
Dear All, one problem is hot at back of my iphone4 when it connect to power source on the wall of my house. But is normal (not hot) when it connect and charging to my lenovo laptop. Why is difference? thanks
-
Hi, I just wrote a C3PO with Dephi 2010. Extending the Tools Menu for my function was easy, but I'm still trying to add a toolbar button. Here is a snip from the code: function CommandFactory.CustomizeToolBar(const Context: WideString; GWToolbar: Ole
-
yo... my MacBook was purchased 15 months ago and guess I am having the same problem with many guys in this section... battery shows 0% at all time with power plugged in with static green light.. supposed to be orange light when battery is not full ri
-
How to install icloud with windows 8.1pro
What is required to install iCloud with Windows 8.1 Pro Operating System. I keep getting install error even though I change compatibility to Windows 7.