Parsing short string of xml
ive been having a terrible time trying to find out how to parse just a short XML string. for example:
<action name="setColor">black</setProperty>
how should I go about parsing it and extracting attributes/textnodes?
none of the xml strings will be more than 1 node deep, and keep in mind that im n00b and have no experience with java XML parsers. thankee
whoops, old xml should read like this:
<action name="setColor">black</action>
Similar Messages
-
How to parse a string containing xml data
Hi,
Is it possible to parse a string containing xml data into a array list?
my string contains xml data as <blood_group>
<choice id ='1' value='A +ve'/>
<choice id ='2' value='B +ve'/>
<choice id ='3' value='O +ve'/>
</blood_group>how can i get "value" into array list?There are lot of Java XML parsing API's available, e.g. JAXP, DOM4J, JXPath, etc.
Of course you can also write it yourself. Look which methods the String API offers you, e.g. substring and *indexOf. -
XML string to XML parsing in JCD
I have stored an XML file as a CLOB in the Oracle DB. While fetching this data into JCD using Oracle OTD, I am getting this CLOB field as a string containing the XML. Now I want to parse this XML string to XML, as I need to map the individual fields to an XSD OTD, which will be my output.
Kindly suggest a way to achieve this.An XSD OTD has an unmarshalFromString() method:
inputFormat.unmarshalFromString( strData );
When putting the XML into the CLOB it could be a good idea to wrap an outputstream into a Writer object in order to make certain that the encoding is correct, depending how the data is represented. When retrieving CLOB data using getCharacterStream() you will get a Reader object where the encoding is already given. -
How to Parse a string into an XML DOM ?
Hi,
I want to parse a String into an XML DOM. Not able to locate any parser which supports that. Any pointers to this?Download Xerces from xml.apache.org. Place the relevant JAR's on your classpath. Here is sample code to get a DOM document reference.
- Saish
public final class DomParser extends Object {
// Class Variables //
private static final DocumentBuilder builder;
private static final String JAXP_SCHEMA_LANGUAGE =
"http://java.sun.com/xml/jaxp/properties/schemaLanguage";
/** W3C schema definitions */
private static final String W3C_XML_SCHEMA =
"http://www.w3.org/2001/XMLSchema";
// Constructors //
static {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(true);
factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
builder = factory.newDocumentBuilder();
builder.setErrorHandler(new ErrorHandler() {
public void warning(SAXParseException e) throws SAXException {
System.err.println("[warning] "+e.getMessage());
public void error(SAXParseException e) throws SAXException {
System.err.println("[error] "+e.getMessage());
public void fatalError(SAXParseException e) throws SAXException {
System.err.println("[fatal error] "+e.getMessage());
throw new XmlParsingError("Fatal validation error", e);
catch (ParserConfigurationException fatal) {
throw new ConfigurationError("Unable to create XML DOM document parser", fatal);
catch (FactoryConfigurationError fatal) {
throw new ConfigurationError("Unable to create XML DOM document factory", fatal);
private DomParser() {
super();
// Public Methods //
public static final Document newDocument() {
return builder.newDocument();
public static final Document parseDocument(final InputStream in) {
try {
return builder.parse(in);
catch (SAXException e) {
throw new XmlParsingError("SAX exception during parsing. Document is not well-formed or contains " +
"illegal characters", e);
catch (IOException e) {
throw new XmlParsingError("Encountered I/O exception during parsing", e);
}- Saish -
Parsing from a string of XML?
Hi there,
I'm using DOM to parse some XML. However, the XML is not in a file, it's in a String. So the DocumentBuilder's parse(...) method takes an InputStream or File object but I'm looking to parse a String. Can anybody help me??
Cheers,
SeanOk I found out a way to parse an XML string:
DocumentBuilder builder = factory.newDocumentBuilder();
StringReader sr = new StringReader(xmlString.toString());
InputSource is = new InputSource(sr);
document = builder.parse(is);
But I'm getting the following error on the parse() line:
[Fatal Error] :1:20: A pseudo attribute name is expected.
org.xml.sax.SAXParseException: A pseudo attribute name is expected.
at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
at test.TestDOM.main(TestDOM.java:61)
The XML string is:
String xmlString = "<?xml version=\"1.0\"><tag><tag_id>250397</tag_id><reader_id>1</reader_id><rssi>74</rssi><date>7/19/2006</date><time>2:59:47 PM</time></tag>";
Can anybody help?
Cheers,
Sean -
I have stored an XML file as a CLOB in the Oracle DB. While fetching this data into JCD in JavaCAPS using Oracle OTD, I am getting this CLOB field as a string containing the XML. Now I want to parse this XML string to XML, as I need to map the individual fields to an XSD OTD, which will be my output.
Kindly suggest a way to achieve this.The forum itself is a good starting point : [http://forum.java.sun.com/thread.jspa?forumID=34&threadID=347151] is a result searching for "parse string"...
-
Dear All,
I have an OSB service which returns an xml form of output in string.
I am calling this OSB service in BPEL but it fails due to this string format recieved by BPEL.
How can I avoid it. I am also trying to convert string to xml but failing to do so.
Any pointers to this would be helpful
Thanks and Regards,
Mitstry setting the Outbound Response HTTP transport header
http:Content-Type=text/xml
or application/xml (even better)
(and of course you should make sure you have fn-bea:inlinedXml() function to turn the String into a XmlObject) -
I am getting the following Error while trying
to compile the SampleMain.java file(Generating an XML document from a given Employee.dtd).
I have set my classpath to use xmlparser.jar.
D:\XMls>javac SampleMain.java
SampleMain.java:65: Can't convert oracle.xml.parser.DTD to oracle.xml.parser.v2.DTD.
main(java.l
ang.String[]).
generator.generate(dtd, doctype_name);Would you check the java parser version you are using? If using java parser V2, the normal lib name is xmlparserv2.jar.
null -
Hi everyone,
i'm just writing a method, that gets a string and a XPath and want writes the string to the specific XPath in my xml document. The problem ist, that the string itself can contain nodes like (e.g. <image> or something else from my dtd, so i got some problems converting the string to xml. Actually i'm trying this:
public static void setEditFragment(String content, String xPath) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse("data.xml");
XPath xpath = XPathFactory.newInstance().newXPath();
Node node = (Node)xpath.evaluate(xPath, document, XPathConstants.NODE);
System.out.println(content);
node.setTextContent(content);
// Use a XSLT transformer for writing the new XML file
Transformer transformer = TransformerFactory.newInstance().newTransformer();
// Set output to IsoLatin1
transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
DOMSource source = new DOMSource( document );
FileOutputStream os = new FileOutputStream("tmp.xml");
StreamResult result = new StreamResult( os );
transformer.transform( source, result );
}but of course this will not work and sets up some cryptic signs in mein xml document....
can anyone give me advice ?
Thanks !Well, if you already have the data XML encoded, then just write them to a file:
http://java.sun.com/docs/books/tutorial/essential/io/index.html
Make sure you encode the data with UTF8:
http://java.sun.com/javase/6/docs/api/java/lang/String.html#getBytes(java.lang.String)
Write "<?xml version="1.0" encoding="utf-8"?>" before the data!
Note however, I generally don't recommend to write XML data by hand. Rather use a framework like JAXB.
-Puce
Edited by: Puce on May 8, 2008 1:36 PM -
Conversion of xml string to xml file
To convert xml string to xml file in java i used
Document XMLDoc=DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader("<root><main>Title</main></root&g t;")));
But it is showing an error as InputSource cannot be resolved
How to rectify thisI assume you mean there is a compiler error? (It helps if you explain your problem instead of just giving a vague description of it.) It sounds like you have to import InputSource. You do know about the import statements that go at the beginning of a Java class, don't you?
-
Error in converting String to XML file
Hi
Please see the code below, basically i want to convert the String
i am having error when parsing xmlFile1, since the xml has some German characters like �
How do i work around it or what is the best way to do it
import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.io.*;
public class TestXMLFile
public TestXMLFile() throws Exception
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
StringBuffer xmlFile = new StringBuffer();
xmlFile.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
xmlFile.append("<ITEMSPECIALNOTES><SPECIALNOTE>unvernderter Nachdruck</SPECIALNOTE></ITEMSPECIALNOTES>");
ByteArrayInputStream byteArray = new ByteArrayInputStream(xmlFile.toString().getBytes());
Document doc = factory.newDocumentBuilder().parse(byteArray);
System.out.println ("String parsed in XML ");
StringBuffer xmlFile1 = new StringBuffer();
xmlFile1.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
xmlFile1.append("<ITEMSPECIALNOTES><SPECIALNOTE>unver�nderter Nachdruck</SPECIALNOTE></ITEMSPECIALNOTES>");
ByteArrayInputStream byteArray1 = new ByteArrayInputStream(xmlFile1.toString().getBytes());
Document doc1 = factory.newDocumentBuilder().parse(byteArray1);
System.out.println ("String1 parsed in XML ");
public static void main(String args[])throws Exception
new TestXMLFile();
}Don't convert to bytes using your system's default encoding but tell the parser that the bytes are encoded in UTF-8.
In fact since you already have chars, don't convert to bytes and make the parser convert back to chars at all. Do this:String string = xmlFile.toString();
Document doc =
factory.newDocumentBuilder().parse(new InputSource(new StringReader(string))); -
Parsing formatted String to Int
How can I parse formatted string to Integer ?
I have a formated string like this $900,000 and I need to convert it to 900000 so I could do calculations with it.
I tried something like this
NumberFormat nf = NumberFormat.getIntegerInstance(request.getLocale());
ttlMargin=nf.parse(screenVal);I got this exception
"java.lang.NumberFormatException: For input string: "$1,050,000""I am working on the JSP file that provides
margins,sales etc. I am reading this data off the
screen where it is beeing displayed according to the
accounting practices.
That's why I get it as a formatted string and why I
am trying covert that string to the numberScreen-scraping is a problematic, bad design. It sounds like what you really want is to call a web service which returns its results as data that a program can understand (XML, for example), not HTML (which is meant more for humans to read). I know, you probably can't change the design at this point... just food for thought. In the meantime, you'll probably have to manually parse those strings yourself by stripping out the '$' and ',' characters and then use parseInt on the result. -
Parse an Aggregate in XML Document using PL/SQL
Hi. I've been successful with parsing a TAG in XML Document stored in CLOB using PL/SQL XML Parser.
However, I need help on how to get the whole aggregate in XML Document stored in CLOB.
sample XML Doc :
<library>
<book>
<title>Oracle Complete Reference</title>
<author>Kevin</Author>
<year>2000</year>
</book>
<video>
<title>Learning C++</title>
<length>2 hours</length>
<video>
</library>
I need a function that will accept an Input which is the aggregate name and will return the aggregate value.
With the sample XML above, say the input is 'VIDEO', the function will return :
<video>
<title>Learning C++</title>
<length>2 hours</length>
<video>
I'll really appreciate any help.
nullI used such an example to parse several Varchar2 strings in a given DB session:
BEGIN
parser := xmlparser.newparser ;
xmlparser.parsebuffer(parser,xmlout) ;
domdoc := xmlparser.getDocument(parser) ;
xmlparser.FREEPARSER(parser) ;
parser.id := -1 ;
nodes := xslprocessor.selectNodes(
xmldom.makenode(domdoc),
'Positionen/Position') ;
for i in 1 .. xmldom.getLength(nodes) loop
node := xmldom.item(nodes,i-1) ;
-- do s/thing with the node
end loop ;
xmldom.freedocument(domdoc) ;
RETURN(komponenten) ;
EXCEPTION
WHEN OTHERS THEN
if parser.id <> -1 then xmlparser.freeparser(parser) ;
end if ;
if domdoc.id <> -1 then xmldom.freedocument(domdoc) ;
end if ;
RAISE ;
END ;
However, after about 2000 of nodes lists parsed, I get an ArrayIndexOutOfBoundsException from XMLNodeCover. Obviously, I should release the nodes or the nodelist, but I have not found any procedure to do this.
Pascal -
Hi,
I need to parse,in CVP 7.0(1), the BAAccountNumber variable passed by the ICM dialer. Is there a built-in java class or other function that would help me do this?
Our BAAccountNumber variable looks something like this: 321|XXX12345678|1901|M. In IP IVR I use the "Get ICM Data" object to read the BAAccountNumber variable from ICM and then I use the "token index" feature to parse the variable (picture below).
Alternately, IP IVR also has a Java class that allows me to do this; the class is "java.lang.String" and the method is "public int indexOf(String,int)"
Is there something equivalent in CVP 7.0(1)?
thanksThanks again for your help. This is what I ended up doing:
This configurable action element takes a string seperated by two "|" (123|123456789|12)
and returns 3 string variables.
you can add more output variables by adding to the Setting array below.
// These classes are used by custom configurable elements.
import com.audium.server.session.ActionElementData;
import com.audium.server.voiceElement.ActionElementBase;
import com.audium.server.voiceElement.ElementData;
import com.audium.server.voiceElement.ElementException;
import com.audium.server.voiceElement.ElementInterface;
import com.audium.server.voiceElement.Setting;
import com.audium.server.xml.ActionElementConfig;
public class SOMENAMEHERE extends ActionElementBase implements ElementInterface
* This method is run when the action is visited. From the ActionElementData
* object, the configuration can be obtained.
public void doAction(String name, ActionElementData actionData) throws ElementException
try {
// Get the configuration
ActionElementConfig config = actionData.getActionElementConfig();
//now retrieve each setting value using its 'real' name as defined in the getSettings method above
//each setting is returned as a String type, but can be converted.
String input = config.getSettingValue("input",actionData);
String resultType = config.getSettingValue("resultType",actionData);
String resultEntityID = config.getSettingValue("resultEntityID",actionData);
String resultMemberID = config.getSettingValue("resultMemberID",actionData);
String resultTFNType = config.getSettingValue("resultTFNType",actionData);
//get the substring
//String sub = input.substring(startPos,startPos+numChars);
String[] BAAcctresults = input.split("\\|");
//Now store the substring into either Element or Session data as requested
//and store it into the variable name requested by the Studio developer
if(resultType.equals("Element")){
actionData.setElementData(resultEntityID,BAAcctresults[0]);
actionData.setElementData(resultMemberID,BAAcctresults[1]);
actionData.setElementData(resultTFNType,BAAcctresults[2]);
} else {
actionData.setSessionData(resultEntityID,BAAcctresults[0]);
actionData.setSessionData(resultMemberID,BAAcctresults[1]);
actionData.setSessionData(resultTFNType,BAAcctresults[2]);
actionData.setElementData("status","success");
} catch (Exception e) {
//If anything goes wrong, create Element data 'status' with the value 'failure'
//and return an empty string into the variable requested by the caller
e.printStackTrace();
actionData.setElementData("status","failure");
public String getElementName()
return "MEDDOC PARSER";
public String getDisplayFolderName()
return "SSC Custom";
public String getDescription()
return "This class breaks down the BAAccountNumber";
public Setting[] getSettings() throws ElementException
//You must define the number of settings here
Setting[] settingArray = new Setting[5];
//each setting must specify: real name, display name, description,
//is it required?, can it only appear once?, does it allow substitution?,
//and the type of entry allowed
settingArray[0] = new Setting("input", "Original String",
"This is the string from which to grab a substring.",
true, // It is required
true, // It appears only once
true, // It allows substitution
Setting.STRING);
settingArray[1] = new Setting("resultType", "Result Type",
"Choose where to store result \n" +
"into Element or Session data",
true, // It is required
true, // It appears only once
false, // It does NOT allow substitution
new String[]{"Element","Session"});//pull-down menu
settingArray[1].setDefaultValue("Session");
settingArray[2] = new Setting("resultEntityID", "EntityID",
"Name of variable to hold the result.",
true, // It is required
true, // It appears only once
true, // It allows substitution
Setting.STRING);
settingArray[2].setDefaultValue("EntityID");
settingArray[3] = new Setting("resultMemberID", "MemberID",
"Name of variable to hold the result.",
true, // It is required
true, // It appears only once
true, // It allows substitution
Setting.STRING);
settingArray[3].setDefaultValue("MemberID");
settingArray[4] = new Setting("resultTFNType", "TFNType",
"Name of variable to hold the result.",
true, // It is required
true, // It appears only once
true, // It allows substitution
Setting.STRING);
settingArray[4].setDefaultValue("TFNType");
return settingArray;
public ElementData[] getElementData() throws ElementException
return null; -
Can anyone say how to transform a XML String to XML document
(eg: String xmlstring="<root><main>Title</main></root>";
How can I transform this to XML Document??
GuhanRight, my mistake, this is what happens when you type code in a browser... hard to compile.
Document XMLDoc=DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader("<root><main>Title</main></root&g t;")))PS. Consider following the online JAXP tutorial: http://java.sun.com/xml/tutorial_intro.html
Maybe you are looking for
-
Ever since i installed firefox 5 beta and the new version of flash, flash crashes on every page with flash on it no matter what version of firefox i run, and flash wont let me roll back to another version. I need flash for my work which is due by the
-
Deleting songs from a single iTunes library?
I recently got a new laptop, and transferred many of my songs off of my desktop computer to my new one. I have home sharing turned on between the two. I want to delete songs from my laptop's library that I don't want, without deleting them from my ma
-
Early 2013 vs. Late 2013 Retina MacBook Pro - which is better? Refurb or New?
Hi, I'm looking to get myself a new (or refurbished) MacBook Pro Retina. And wondering which one to get (i.e. from the list below). Brand New (Late-2013) - $2450 (after corporate discount): CPU 2.3 Ghz (Haswell) 16GB RAM 512 GB SSD Refurbished (Late-
-
Within my query, I have a WHERE statement: WHERE Left(t_item,2) NOT LIKE '%-' AND Left(t_item,2) NOT LIKE '_%' This was to exclude the underscore character. I was told this was the only non number or letter used. Of course now I am finding out that t
-
Laserjet m1217 will not print through easyprint on windows 2008 server 64Bit
We have a client that has the LaserJet M1217 that is connecting to our Window 2008 Server SP2 64Bit via Remote Desktop. Easyprint recognizes the printer, but will not even print a test page. We get a FAIL message. We either need to know how to pri