How to parse XML content in JMS Message...
Hi everybody,
I am currently developing a Message-Driven Bean and has some problem parsing the XML data that contains in the JMS body.
The XML data is contained in TextMessage (JMS message type) and in order to parse the data, I need to use the DOM builder, which is expecting to read from a file (e.g. abc.xml).
My question is how can I use TextMessage (can be output to a String) as the input source instead of a file.
Thanks in advance.
Hi Boon,
"Boon Keong" <[email protected]> wrote in message
news:3dd46800$[email protected]..
I am currently developing a Message-Driven Bean and has some problemparsing the XML data that contains in the JMS body.
>
The XML data is contained in TextMessage (JMS message type) and in orderto parse the data, I need to use the DOM builder, which is expecting to read
from a file (e.g. abc.xml).
>
My question is how can I use TextMessage (can be output to a String) asthe input source instead of a file.
What about this:
DocumentBuilder db = ...
Document doc = db.parse(new InputSource(new
StringReader(textMessage.toString()));
or
Document doc = db.parse(new
ByteArrayInputStream(textMessage.toString().getBytes()));
Regards,
Slava Imeshev
Similar Messages
-
Does JMS parse xml content in TextMessages
Hi
I am working on WLS 6.1sp2 and I am using jms TextMessage type of message to
send XML messages from one subsystem to another. I have added an XML registry
for my version of XML parser. Now I do not have any entries for the entity declarations
nor for the parser entries in the registry.
When I send in an XML message in a TextMessage envelope I find the following
errors in the log.
<Jun 9, 2003 3:56:57 PM PDT> <Error> <XML> <Failed to parse given XML document.
Failed to retrieve PUBLIC id. The root element is required in a well-formed docu
ment.>
<Jun 9, 2003 3:56:57 PM PDT> <Error> <XML> <Failed to open XML document. Failed
to retrieve PUBLIC id or SYSTEM id from the document. Decrease the number of cha
r between the beginning of the document and its root element.>
<Jun 9, 2003 3:56:57 PM PDT> <Error> <XML> <Failed to parse given XML document.
Failed to retrieve SYSTEM id. The root element is required in a well-formed docu
ment.>
<Jun 9, 2003 3:56:57 PM PDT> <Error> <XML> <Failed to open XML document. Failed
to retrieve PUBLIC id or SYSTEM id from the document. Decrease the number of cha
r between the beginning of the document and its root element.>
<Jun 9, 2003 3:56:57 PM PDT> <Error> <XML> <Failed to parse given XML document.
Failed to retrieve root tag. The root element is required in a well-formed docum
ent.>
<Jun 9, 2003 3:56:57 PM PDT> <Error> <XML> <Could not instantiate factory class
specified in the Server console. Invalid parameters: at least one of publicId,
s
ystemId, rootTag must be non-null>
[ChangeAwareClassLoader] : Name is : META-INF/services/org.apache.xerces.xni.par
ser.XMLParserConfiguration
<Jun 9, 2003 3:56:57 PM PDT> <Error> <XML> <Failed to open XML document. Failed
to retrieve PUBLIC id or SYSTEM id from the document. Decrease the number of cha
r between the beginning of the document and its root element.>
<Jun 9, 2003 3:56:57 PM PDT> <Error> <XML> <Failed to parse given XML document.
Failed to retrieve PUBLIC id. The root element is required in a well-formed docu
ment.>
Now from the logs I understand that the message is being parsed and since the
parser does not find any PUBLIC ID or SYSTEM id it dumps the error, since I am
using schemas there is none of the PUBLIC and SYSTEM ids in my xml, also this
is not logged by any component of my subsystems, this is a weblogic XML Service
log and when I trace through the code I find that it comes up after the first
subsystem sends the message and before the second subsystem receives it.
The question then is does JMS parse XML content in TextMessages and if so how
can I disable that parsing?
Thanks
Sandeep
JMS does not automatically parse TextMessages. Check the XML declaration in
your application's deployment descriptors. That's often the source of this
error.
FYI, you can use XMLMessage for xml payloads. As far as I can remember, the
XMLMessage is an extension of the TextMessage with xml parsing built in.
Adarsh
"Sandeep Nayak" <[email protected]> wrote in message
news:[email protected]...
>
> Hi
>
> I am working on WLS 6.1sp2 and I am using jms TextMessage type of message
to
> send XML messages from one subsystem to another. I have added an XML
registry
> for my version of XML parser. Now I do not have any entries for the entity
declarations
> nor for the parser entries in the registry.
>
> When I send in an XML message in a TextMessage envelope I find the
following
> errors in the log.
>
> <Jun 9, 2003 3:56:57 PM PDT> <Error> <XML> <Failed to parse given XML
document.
> Failed to retrieve PUBLIC id. The root element is required in a
well-formed docu
> ment.>
> <Jun 9, 2003 3:56:57 PM PDT> <Error> <XML> <Failed to open XML document.
Failed
> to retrieve PUBLIC id or SYSTEM id from the document. Decrease the number
of cha
> r between the beginning of the document and its root element.>
> <Jun 9, 2003 3:56:57 PM PDT> <Error> <XML> <Failed to parse given XML
document.
> Failed to retrieve SYSTEM id. The root element is required in a
well-formed docu
> ment.>
> <Jun 9, 2003 3:56:57 PM PDT> <Error> <XML> <Failed to open XML document.
Failed
> to retrieve PUBLIC id or SYSTEM id from the document. Decrease the number
of cha
> r between the beginning of the document and its root element.>
> <Jun 9, 2003 3:56:57 PM PDT> <Error> <XML> <Failed to parse given XML
document.
> Failed to retrieve root tag. The root element is required in a well-formed
docum
> ent.>
> <Jun 9, 2003 3:56:57 PM PDT> <Error> <XML> <Could not instantiate factory
class
> specified in the Server console. Invalid parameters: at least one of
publicId,
> s
> ystemId, rootTag must be non-null>
> [ChangeAwareClassLoader] : Name is :
META-INF/services/org.apache.xerces.xni.par
> ser.XMLParserConfiguration
> <Jun 9, 2003 3:56:57 PM PDT> <Error> <XML> <Failed to open XML document.
Failed
> to retrieve PUBLIC id or SYSTEM id from the document. Decrease the number
of cha
> r between the beginning of the document and its root element.>
> <Jun 9, 2003 3:56:57 PM PDT> <Error> <XML> <Failed to parse given XML
document.
> Failed to retrieve PUBLIC id. The root element is required in a
well-formed docu
> ment.>
>
> Now from the logs I understand that the message is being parsed and since
the
> parser does not find any PUBLIC ID or SYSTEM id it dumps the error, since
I am
> using schemas there is none of the PUBLIC and SYSTEM ids in my xml, also
this
> is not logged by any component of my subsystems, this is a weblogic XML
Service
> log and when I trace through the code I find that it comes up after the
first
> subsystem sends the message and before the second subsystem receives it.
>
> The question then is does JMS parse XML content in TextMessages and if so
how
> can I disable that parsing?
>
> Thanks
>
> Sandeep
-
How to parse XML for internal table
hi guys, I would like to know how to parse xml for an internal table. I explain myself.
Let's say you have a purchase order form where you have header data & items data. In my interactive form, the user can change the purchase order quantity at the item level. When I received back the pdf completed by mail, I need to parse the xml and get the po qty that has been entered.
This is how I do to get header data from my form
lr_ixml_node = lr_ixml_document->find_from_name( name = ''EBELN ).
lv_ebeln = lr_ixml_node->get_value( ).
How do we do to get the table body??
Should I used the same method (find_from_name) and passing the depth parameter inside a do/enddo?
thanks
Alexandre GiguereAlexandre,
Here is an example. Suppose your internal table is called 'ITEMS'.
lr_node = lr_document->find_from_name('ITEMS').
lv_num_of_children = lr_node->num_children( ).
lr_nodechild = lr_node->get_first_child( ).
do lv_num_of_children times.
lv_num_of_attributes = lr_nodechild->num_children( ).
lr_childchild = lr_nodechild->get_first_child( ).
do lv_num_of_attributes times.
lv_value = lr_childchild->get_value( ).
case sy-index.
when 1.
wa_item-field1 = lv_value
when 2.
wa_item-field2 = lv_value.
endcase.
lr_childchild = lr_childchild->get_next( ).
enddo.
append wa_item to lt_item.
lr_nodechild = lr_nodechild->get_next( ).
enddo. -
i've searched on how to parse xml against xsd,dtd,etc.. without the needs of internet connection..
but unfortunately, only the xsd file can be set locally and still there needs the internet connection for the other features, properties.
XML: GML file input from gui
XSD: input from gui
javax.xml
package demo;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.xml.sax.SAXException;
public class Sample1WithJavaxXML {
public static void main(String[] args) {
URL schemaFile = null;
try {
//schemaFile = new URL("http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd");
File file0 = new File("AppSchema-C01-v1_0.xsd");
schemaFile = new URL(file0.toURI().toString());
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
//Source xmlFile = new StreamSource(new File("web.xml"));
Source xmlFile = new StreamSource(new File("C01.xml"));
SchemaFactory schemaFactory = SchemaFactory
.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
//File file1 = new File("XMLSchema.dtd");
//SchemaFactory schemaFactory = SchemaFactory
//.newInstance("javax.xml.validation.SchemaFactory:XMLSchema.dtd");
Schema schema = null;
try {
schema = schemaFactory.newSchema(schemaFile);
} catch (SAXException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
Validator validator = schema.newValidator();
try {
validator.validate(xmlFile);
System.out.println(xmlFile.getSystemId() + " is valid");
} catch (SAXException e) {
System.out.println(xmlFile.getSystemId() + " is NOT valid");
System.out.println("Reason: " + e.getLocalizedMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}Xerces
package demo;
import java.io.File;
import java.util.Date;
import org.apache.xerces.parsers.DOMParser;
public class SchemaTest {
private String xmlFile = "";
private String xsdFile = "";
public SchemaTest(String xmlFile, String xsdFile) {
this.xmlFile = xmlFile;
this.xsdFile = xsdFile;
public static void main (String args[]) {
File file0 = new File("AppSchema-C01-v1_0.xsd");
String xsd = file0.toURI().toString();
SchemaTest testXml = new SchemaTest("C01.xml",xsd);
testXml.process();
public void process() {
File docFile = new File(xmlFile);
DOMParser parser = new DOMParser();
try {
parser.setFeature("http://xml.org/sax/features/validation", true);
parser.setFeature("http://apache.org/xml/features/validation/schema", true);
parser.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
xsdFile);
ErrorChecker errors = new ErrorChecker();
parser.setErrorHandler(errors);
System.out.println(new Date().toString() + " START");
parser.parse(docFile.toString());
} catch (Exception e) {
System.out.print("Problem parsing the file.");
System.out.println("Error: " + e);
System.out.println(new Date().toString() + " ERROR");
return;
System.out.println(new Date().toString() + " END");
}Thanks a lot Sir DrClap..
I tried to use and implement the org.w3c.dom.ls.LSResourceResolver Interface which is based on the SAX2 EntityResolver.
please give comments the way I implement it. Here's the code:
LSResourceResolver Implementation
import org.w3c.dom.ls.LSInput;
import org.w3c.dom.ls.LSResourceResolver;
import abc.xml.XsdConstant.Path.DTD;
import abc.xml.XsdConstant.Path.XSD;
public class LSResourceResolverImpl implements LSResourceResolver {
public LSResourceResolverImpl() {
* {@inheritDoc}
@Override
public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
LSInput input = new LSInputImpl(publicId, systemId, baseURI);
if ("http://www.w3.org/2001/xml.xsd".equals(systemId)) {
input.setByteStream(classLoader.getResourceAsStream(XSD.XML));
} else if (XsdConstant.PUBLIC_ID_XMLSCHEMA.equals(publicId)) {
input.setByteStream(classLoader.getResourceAsStream(DTD.XML_SCHEMA));
} else if (XsdConstant.PUBLIC_ID_DATATYPES.equals(publicId)) {
input.setByteStream(classLoader.getResourceAsStream(DTD.DATATYPES));
return input;
}I also implement org.w3c.dom.ls.LSInput
import java.io.InputStream;
import java.io.Reader;
import org.w3c.dom.ls.LSInput;
public class LSInputImpl implements LSInput {
private String publicId;
private String systemId;
private String baseURI;
private InputStream byteStream;
private String stringData;
public LSInputImpl(String publicId, String systemId, String baseURI) {
super();
this.publicId = publicId;
this.systemId = systemId;
this.baseURI = baseURI;
//getters & setters
}Then, here's the usage/application:
I create XMLChecker class (SchemaFactory implementation is Xerces)
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.XMLConstants;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import abc.xml.XsdConstant.Path.XSD;
public class XMLChecker {
private ErrorMessage errorMessage = new ErrorMessage();
public boolean validate(String filePath){
final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
List<Source> schemas = new ArrayList<Source>();
schemas.add(new StreamSource(classLoader.getResourceAsStream(XSD.XML_SCHEMA)));
schemas.add(new StreamSource(classLoader.getResourceAsStream(XSD.XLINKS)));
schemas.add(new StreamSource(classLoader.getResourceAsStream("abc/xml/AppSchema.xsd")));
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
schemaFactory.setResourceResolver(new LSResourceResolverImpl());
try {
Schema schema = schemaFactory.newSchema(schemas.toArray(new Source[schemas.size()]));
Validator validator = schema.newValidator();
validator.setErrorHandler(new ErrorHandler() {
@Override
public void error(SAXParseException e) throws SAXException {
errorMessage.setErrorMessage(e.getMessage());
errorMessage.setLineNumber(e.getLineNumber());
errorMessage.setColumnNumber(e.getLineNumber());
throw e;
@Override
public void fatalError(SAXParseException e) throws SAXException {
errorMessage.setErrorMessage(e.getMessage());
errorMessage.setLineNumber(e.getLineNumber());
errorMessage.setColumnNumber(e.getLineNumber());
throw e;
@Override
public void warning(SAXParseException e) throws SAXException {
errorMessage.setErrorMessage(e.getMessage());
errorMessage.setLineNumber(e.getLineNumber());
errorMessage.setColumnNumber(e.getLineNumber());
throw e;
StreamSource source = new StreamSource(new File(filePath));
validator.validate(source);
} catch (SAXParseException e) {
return false;
} catch (SAXException e) {
errorMessage.setErrorMessage(e.getMessage());
return false;
} catch (FactoryConfigurationError e) {
errorMessage.setErrorMessage(e.getMessage());
return false;
} catch (IOException e) {
errorMessage.setErrorMessage(e.getMessage());
return false;
return true;
public ErrorMessage getErrorMessage() {
return errorMessage;
}Edited by: erossy on Aug 31, 2010 1:56 AM -
Hi! I'm having problems parsing an xml string. I've done DOM and SAX parsing before. But both of them either parse a file or data from an input source. I don't think they handle strings. I also don't want to write the string into a file just so I can use DOM or SAX.
I'm looking for something where I could simply do:
Document doc = documentBuilder.parse( myXMLString );
So the heirarchy is automatically established for me. Then I could just do
Element elem = doc.getElement();
String name = elem.getTagName();
These aren't the only methods I would want to use. Again, my main problem is how to parse xml if it is stored in a string, not a file, nor comming from a stream.
thanks!But both of them either parse a file or data from an input source. I don't think they handle strings.An InputSource can be constructed with a Reader as input. One useful subclass of Reader is StringReader, so you'd use something likeDocument doc = documentBuilder.parse(new InputSource(new StringReader(myXMLString)));
-
How to parsing xml data in sql statement??
Hi friends, I have a table which contain column as clob ,stores in xml format, for example my column contain xml data like this
<Employees xmlns="http://TargetNamespace.com/read_emp">
<C1>106</C1>
<C2>Harish</C2>
<C3>1998-05-12</C3>
<C4>HR</C4>
<C5>1600</C5>
<C6>10</C6>
</Employees>
Then how to extract the data in above xml column data using SQL statement...Duplicate post
How to parsing xml data in sql statement?? -
How to parse xml file in midlet
Hi Guys,
i wish to parse xml file and display it in my midlet. i found api's supporting xml parsing in j2se ie., in java.net or j2se 5.0. Can u please help me what package to use in midlet?
how to parse xml info and display in midlet? Plz reply soon......Thanks in advance....i 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 -
Hello,
Can anyone help me to know how to parse xml in sap abap.
I have a xml file which i want to parse and store it in internal table.
<?xml version="1.0" encoding="UTF-8"?>##<data><name>menaka<name></data>
Regards,
Menaka.H.BHello,
For how to get the node name, you have to refer to this :
[https://wiki.sdn.sap.com/wiki/display/ABAP/Upload%20XML%20file%20to%20internal%20table|https://wiki.sdn.sap.com/wiki/display/ABAP/Upload%20XML%20file%20to%20internal%20table]
Check the code after:
WHEN if_ixml_node=>co_node_element
It tells you how to get the node name.
BR,
Suhas -
How to parse xml and import to execel
pls let me know how to parse XML file and import all data to execel sheet.
Hi Mandya,
This is outside of the normal use case for TestStand. It would be best to use a code module (developed in LabVIEW, C, or any other language) to accomlish this and then call it from a step in TestStand. You can find examples on ActiveX here:
http://forums.ni.com/t5/NI-TestStand/Controlling-Excel-from-TestStand-with-Activex-Automation/td-p/1...
I hope this helps.
Frank L.
Software Product Manager
National Instruments -
How to read XML content from IPortalComponentRequest and parse them
Hi ,
I have a portal application.The application has 2 components(Comp1,comp2).
Comp1 is JspDynpage and Comp2 is AbstractPortalComponent.
Comp1- has a iframe element which point to the external url and has a parameter return_url.
retrun_url has a value as url to Comp2(http://ibm0343:50000/irj/servlet/prt/portal/prtroot/NewUrlProj.NewUrlComp)
When an event occurs in the external site,i suppose to receive XML content in return_url(ie Comp2),how can i check using the request if the received content is XML and how do i parse them.
I have already seen blogs from Prakash singh in which it refers a xml fixed location in webserver.Hi Detlev,
i am reposting this once again as the previous
reply didnt align good.
Thanks for your reply.The scenario is that
My portal application has to communicate with external GIS(Graphical information system)
service provider client application.
They say that i have to use iframe in my portal application.
Here is the snipet of the iframe tags.
<iframe
id="Nedbrowser"
name="Nedbrowser"
width="100%"
height="100%"
frameborder="no"
marginheight="0"
marginwidth="0"
scrolling="no"
style="position:absolute; top:0; left:0; width:800; height:400; z-index:100; visibility:visible"
src="http://nbg.nedg.nl/nbgint/NBG_INT_main.asp?action=CHART&datasource=NBGMV&product=INTERNET&size_x=300&size_y=300&result_frame=Results&
result_url=http://ibm0343:50000/irj/servlet/prt/portal/prtroot/NewUrlProj.NewUrlComp&
default_centre_x=256000&default_centre_y=471000&default_width=0.5">
</iframe>
<iframe
id="Results"
name="Results"
width="100%"
height="100%"
frameborder="no"
marginheight="0"
marginwidth="0"
scrolling="no"
style="position:absolute; top:400; left:0; width:800; height:200; z-index:100; visibility:visible"
src="about:blank">
</iframe>
When my portal application is started, comes the GIS map in the iframe with in my portal application.
When the user clicks in the area of the map,Gis application returns xml data to the return_url.
The reurn_url is my PortalAbstractComponent in which i have to parse the xml and use it for further processing in R3 system. -
How to Parse XML into String in BPEL?
Hi,
Can anyone tell me, how can I parse XML into String?
I am taking input from File Adapter, File adapter is reading that XML.
Then in assign activity i am using XPath expression(built functions) using XMLParser(),doTranslateToNative() etc.. many functions I have tried but XML is not getting parsed into String Variable.
Please help me asap.
Thanks
ShikhaThanks a lot Eric.
I am trying this, oraext:get-content-as-string('receiveInput_Read_InputVariable','body','/ns3:orders')
but getting this error
<bpelFault><faultType>0</faultType><subLanguageExecutionFault xmlns="http://schemas.oracle.com/bpel/extension"><part name="summary"><summary>XPath expression failed to execute. An error occurs while processing the XPath expression; the expression is oraext:get-content-as-string('receiveInput_Read_InputVariable','body','/ns3:orders'). The XPath expression failed to execute; the reason was: internal xpath error. Check the detailed root cause described in the exception message text and verify that the XPath query is correct. </summary></part><part name="code"><code>XPathExecutionError</code></part></subLanguageExecutionFault></bpelFault> -
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 -
How to parse xml (kXML)
I have some problems when I try to parse xml with the kXML parser. My xml doc looks like this:
<?xml version="1.0" encoding="utf-8" ?>
- <dsGreenRoom>
- <Rooms>
- <RoomsInfo>
<ID>1</ID>
<Name>Rum 101</Name>
<Type>Dubbelrum</Type>
<NumberOfBeds>2</NumberOfBeds>
<Rate>980,00</Rate>
<Currency>SEK</Currency>
<Description>Ett genomtrevligt rum</Description>
</RoomsInfo>
- <RoomsInfo>
<ID>2</ID>
<Name>Mellanrummet</Name>
<Type>Enkelrum</Type>
<NumberOfBeds>1</NumberOfBeds>
<Rate>650,00</Rate>
<Currency>SEK</Currency>
<Description>Ett litet tr?ngt rum i mitten</Description>
</RoomsInfo>
- <RoomsInfo>
<ID>3</ID>
<Name>Rum 102</Name>
<Type>Flerb?ddsrum</Type>
<NumberOfBeds>3</NumberOfBeds>
<Rate>1250,00</Rate>
<Currency>SEK</Currency>
<Description>Ett ?nnu trevligare rum</Description>
</RoomsInfo>
</Rooms>
</dsGreenRoom>
And my code looks like this:
KXmlParser parser = new KXmlParser();
parser.setInput(is, null);
Document doc = new Document();
doc.parse(parser);
int child_count = root.getChildCount();
System.out.println("child = " + child_count + "\n");
for (int i=0; i < child_count; i++) {
if (root.getType(i) == Node.ELEMENT) {
Element kid = root.getElement(i);
System.out.println("kid = " + kid.getName());
int babies = kid.getChildCount();
System.out.println("babies = " + babies);
for (int j=0; j < babies; j++) {
if (kid.getType(j) == Node.ELEMENT) {
Element room = kid.getElement(j);
System.out.println("room.getType() = " + room.getType(j));
if (room.getName().equals("ID")) {
System.out.println("elName.getName() = " + room.getName());
System.out.println("elName.geText() = " + room.getText(j));
else if (room.getName().equals("Name")) {
System.out.println("elName.getName() = " + room.getName());
System.out.println("elName.geText() = " + room.getText(j));
} // end for(int j...)
} // end if (root.getType(i)
} //for (int i...)
The problem is that I don't know how to get the values out of the tags:
<ID>1</ID>
<Name>Rum 101</Name>
<Type>Dubbelrum</Type>
<NumberOfBeds>2</NumberOfBeds>
<Rate>980,00</Rate>
<Currency>SEK</Currency>
<Description>Ett genomtrevligt rum</Description>
It's no problem to get the value from the firsts i.e. <ID> but I don't know how to get the value from <Name> ... <Description>. I have looked att examples but I don't understand how to do this. Can someone please help me =)okay, sorry, I only read the half of your problem ;-)
You can read the content using the getText(0) method. the 0 indicates the number of the children which you want to get. That is always a 0 because you have always just one text-children in your text-tags. The content is again a children of type text!
hth
Kay -
How to Parse XML with SAX and Retrieving the Information?
Hiya!
I have written this code in one of my classes:
/**Parse XML File**/
SAXParserFactory factory = SAXParserFactory.newInstance();
GameContentHandler gameCH = new GameContentHandler();
try
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(recentFiles[0], gameCH);
catch(javax.xml.parsers.ParserConfigurationException e)
e.printStackTrace();
catch(java.io.IOException e)
e.printStackTrace();
catch(org.xml.sax.SAXException e)
e.printStackTrace();
/**Parse XML File**/
games = gameCH.getGames();And here is the content handler:
import java.util.ArrayList;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
class GameContentHandler extends DefaultHandler
private ArrayList<Game> games = new ArrayList<Game>();
public void startDocument()
System.out.println("Start document.");
public void endDocument()
System.out.println("End document.");
public void startElement(String namespaceURI, String localName, String qualifiedName, Attributes atts) throws SAXException
public void endElement(String namespaceURI, String localName, String qualifiedName) throws SAXException
public void characters(char[] ch, int start, int length) throws SAXException
/**for (int i = start; i < start+length; i++)
System.out.print(ch);
public ArrayList<Game> getGames()
return games;
}And here is the xml i am trying to parse:<?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?>
<Database>
<Name></Name>
<Description></Description>
<CurrentGameID></CurrentGameID>
<Game>
<gameID></gameID>
<name></name>
<publisher></publisher>
<platform></platform>
<type></type>
<subtype></subtype>
<genre></genre>
<serial></serial>
<prodReg></prodReg>
<expantionFor></expantionFor>
<relYear></relYear>
<expantion></expantion>
<picPath></picPath>
<notes></notes>
<discType></discType>
<owner></owner>
<location></location>
<borrower></borrower>
<numDiscs></numDiscs>
<discSize></discSize>
<locFrom></locFrom>
<locTo></locTo>
<onLoan></onLoan>
<borrowed></borrowed>
<manual></manual>
<update></update>
<mods></mods>
<guide></guide>
<walkthrough></walkthrough>
<cheats></cheats>
<savegame></savegame>
<completed></completed>
</Game>
</Database>I have been trying for ages and just can't get the content handler class to extract a gameID and instantiate a Game to add to my ArrayList! How do I extract the information from my file?
I have tried so many things in the startElement() method that I can't actually remember what I've tried and what I haven't! If you need to know, the Game class instantiates with asnew Game(int gameID)and the rest of the variables are public.
Please help someone...OK, how's this?
public void startElement(String namespaceURI, String localName, String qualifiedName, Attributes atts) throws SAXException
current = "";
public void endElement(String namespaceURI, String localName, String qualifiedName) throws SAXException
try
if(qualifiedName.equals("Game") || qualifiedName.equals("Database"))
{return;}
else if(qualifiedName.equals("gameID"))
{games.add(new Game(Integer.parseInt(current)));}
else if(qualifiedName.equals("name"))
{games.get(games.size()-1).name = current;}
else if(qualifiedName.equals("publisher"))
{games.get(games.size()-1).publisher = current;}
etc...
else
{System.out.println("ERROR - Qualified Name found in xml that does not exist as databse field: " + qualifiedName);}
catch (Exception e) {} //Ignore
public void characters(char[] ch, int start, int length) throws SAXException
current += new String(ch, start, length);
} -
How to parse XML files from normal FTP Servers?
I want to parse xml files from a normal FTP Servers , NOT the sap application severs itself. How can i do that?
I know how to use the SAPFTP getting and putting files ,but I don't want to download and then parse it.
Who knows how to parse it directly? I Just need to read the contents into a database.
Thanks.I want to parse xml files from a normal FTP Servers , NOT the sap application severs itself. How can i do that?
I know how to use the SAPFTP getting and putting files ,but I don't want to download and then parse it.
Who knows how to parse it directly? I Just need to read the contents into a database.
Thanks.
Maybe you are looking for
-
Cisco mobile does not running in the background ont my ipad
Hi I have a Cisco Callmanager 7.1.5, an ASA5510, an Iphone and an Ipad I have configure the VPN on my iphone and my ipad and I can make a VPN connection to the ASA through the WIFI I have configure the Cisco Mobile 8.1.2.3245 on my iphone and my ipa
-
DW CS5: CollapsiblePanels are not well in IE
Hi NG, i have some CollapsiblePanel on my side. It is working perfect under FF or Safari. But under IE - 6 or 8 or 9 - i can ope a panel. But than if i open a other one, it flashed me all the time some other panel too. It looks like a freak show! Is
-
hi all, i would like to know how to add certain fields to the standard program RFBABL00. i want to add fields like vendor/customer id, document clearing date etc. pls reply
-
Help please re Lion, importing exchange 2008 into Mac Mail
If anyone can help me - it would be fantastic! Am trying to sync iphone4, ipad2 and mac book pro - which originally had snow leopard... now just upgraded to Lion 10.7.3 Have email on POP server which is apparently an IMAP enabled - exchange account..
-
I'm having trouble with the purchase of currency in the game Casyle Clash locks! In order status says "Back" returns so what? Money at stake so I have not returned!