JDOM: Parsing XML String, getting error

Hello,
I am new to this forum, so please forgive me
if this has already been asked before. I want to
parse an XML string. I know the JDOM parser works
great with a file, but apparently I have been
unsuccessful parsing an XML String. Below is how I
initialize the parser:
import java.io.*; //Import proper packages
import org.jdom.*;
import org.jdom.input.*;
import org.jdom.output.*;
import java.util.*;
import java.lang.*;
public class XMLParser{
private Document doc = null;
public XMLParser(String xml){
doc = readDocument(xml);
private Document readDocument(String xml) {
try {
SAXBuilder builder = new SAXBuilder();
org.jdom.Document result = builder.build(new
StringReader(xml));
return result;
} catch(JDOMException e) {
e.printStackTrace();
} catch(NullPointerException e) {
e.printStackTrace();
return null;
} //readDocument
The following is the error I receive:
JDOM/xmlparser.java [81:1] cannot resolve symbol
symbol : method build (java.io.StringReader)
location: class org.jdom.input.SAXBuilder
org.jdom.Document result = builder.build(new
StringReader(filename));
--> Arrow pointing to builder.build
Please if someone can help me out. If JDOM does not
have this feature, then can someone please recommend a
parser that can parse an XML String.

Thank you for your help, although it seems like it was JDom 9 beta. When I tried with JDOM 8 beta, everything worked fine even with the StringReader. So if anyone is having similar problems with JDom 9 then try with JDom 8.

Similar Messages

  • Spry can not  parse xml string

    while designind an mvc architecutre in php I found display
    data on site was slow so I generate a xml sheet an used spry Data
    loading was fast an dproduced and I also performed many operations
    like sorting ,galeery making ..etc... but main thing is that I can
    not parse a xml string using spry only a xml file can be parsed
    my application required to parse xml string

    I'm not sure if this is valid in your situation, but OC4J comes with Oracle XMLParser.
    Simply use the JAXP API to parse/build/modify XML and the Oracle XMLParser implementation will be used behind the scenes.
    If you must use xerces/xalan, try putting the jars in OC4J_HOME/j2ee/home/lib instead.
    HTH //Anders

  • Getting Error while creating Document object  after  parsing XML String

    Hi All,
    I have been trying to parse an XML string using the StringReader and InputSource interface but when I am trying to create Document Object using Parse() method getting error like
    [Fatal Error] :2:6: The processing instruction target matching "[xX][mM][lL]" is not allowed.
    seorg.xml.sax.SAXParseException: The processing instruction target matching "[xX][mM][lL]" is not allowed.
    Please find the code below which i have been experimenting with:
    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    import java.io.StringReader;
    import java.util.List;
    import java.util.*;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    import java.io.*;
    public class TestMain {
         public static void main(String[] args) {
              String file = "";
              file = loadFileContent("C:\\Test.xml");
              System.out.println("contents >> "+file);
              parseQuickLinksFileContent(file);
    public static void parseQuickLinksFileContent(String fileContents) {
    PWMQuickLinksModelVO objPWMQuickLinksModelVO = new PWMQuickLinksModelVO();
         try {
    DocumentBuilderFactory factory =           DocumentBuilderFactory.newInstance();
         DocumentBuilder builder = factory.newDocumentBuilder();
         StringReader objRd = new StringReader(fileContents);
         InputSource objIs = new InputSource(objRd);
         Document document = builder.parse(objIs); // HERE I am getting Error.
         System.out.println(document.toString());
    What is happening while I am using builder.parse() method ???
    Thanks,
    Rajendra.

    Getting following error
    [Fatal Error] :2:6: The processing instruction target matching "[xX][mM][lL]" is not allowed.
    seorg.xml.sax.SAXParseException: The processing instruction target matching "[xX][mM][lL]" is not allowed.

  • Getting null value while parsing "XML String" with  encoding WINDOWS-1252.

    Hi,
    when I am converting the Follwoing "xml string " to Document, I am getting the "null" as a document value.
        String strXML =  "<?xml version="1.0" encoding="WINDOWS-1252"?>
                              <category name="SearchByAttributes" value="Search By Attributes">
                                <item name="ORDER_LINE_ID" description="Application Search Attributes" >
                                   <attribute name="Sequence" value="0001"/>
                                 </item>
                                </category>"      
    My "xml string" has the encoding vaule: WINDOWS-1252.
    I am using the following code to convert the "xml string" to Document. I am getting the Document values as a "null" while converting the above "string xml"
            String strXML = //my above string xml.
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            docBuilderFactory.setIgnoringElementContentWhitespace(true);
            docBuilder = docBuilderFactory.newDocumentBuilder();
            doc = docBuilder.parse(new InputSource(new StringReader(strXML)));              
            System.out.println("doc value.."+doc)//I am getting null value for "doc".
    Can anyone help me to resolve the issue.

    Thagelapally wrote:
    I am coverting the below "XML string" to Document, once it is converted I am reading that Document,which have an "attribue" Element in.
      String strXML = "<?xml version="1.0" encoding="WINDOWS-1252"?>
    <category name="SearchByAttributes" value="Search By Attributes">
    <item name="ORDER_LINE_ID" description="Application Search Attributes" >
    <attribute name="Sequence" value="0001"/>
    </item>
    </category>" I am using the above code to read the Document. When run the code in "OC4J Server" and using Jdeveloper as an editor,I am able to perfectly read the "attribute" element in the document with out any problem.Println statement printing as I expected.
    System.out.println("Element Name..."+listOfAtt.getNodeName());
    //getting Element Name as...."attribute"(as expected)
    System.out.println("Element Attibrute list....."+elementAtt);
    //getting Element Attribute list as an...."oracle.xml.parser.v2.XMLAttrList@afe"But when run the same code(reading the same Document) in Tomcat and Eclipse,println satatement not printing as i expected.
    System.out.println("Element Name..."+listOfAtt.getNodeName());
    //getting Element Name as...."#text"(I am expecting output value "attribute" but it is printing "#text" which i don't know)
    System.out.println("Element Attibrute list....."+elementAtt);
    //getting Element Attribute list as an...."null"(I am expecting output value object reference but it is printing "null"
    (without the rest of the code, i'm guessing that) most likely you are grabbing the first child node of the item element. however, you are not accounting for some text nodes that are most likely in that list, like the whitespace between the item element and the attribute element. please go read some tutorials on xml, there are thousands of them out there, and they will answer all you initial questions much more efficiently than posting each step to the forums.

  • How to parse XML string fetched from the database

    i want to parse the XML string which is fetched from the oracle database.
    i have inserted the string in xml format in the database. The type of the field in which it is inserted is varchart2.
    I am successfully getting it using jdbc, storing it in a String.
    Now it is appended with xml version 1.0 and string is ready for parsing.
    Now i am making following programming.
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = Builder.parse(xmlString);
    Element root = doc.getDocumentElement();
    NodeList node = root.getElementsByTagName("product");
    But i am getting IOException at the statement
    Document doc = Builder.parse(xmlString);
    there fore i request u to kindly help me in solving this error.
    -regards
    pujan

    DocumentBuilder does not have a method parse with xml string as aparameter. The string should be a xml document uri.
    Convert xml string to StringReader.
    parse(new InputSource(new StringReader(xmlString)));

  • Parsing XML Strings

    I am getting an XML String from a web-service.. Is there a method inside of BPM to parse this xml string?

    Hi, my xml string is:-
    <?xml version="1.0" encoding="UTF-8" ?>
    <ns2:Exception xmlns:ns2="http://example.com/" >
         <errorCode>0</errorCode>
         <errorSubcode>0</errorSubcode>
         <message>Connection refused</message>
         <messageWithProperties>Connection refused
         Error Code=[0]
         ticketId=[1]
         fileName=[testFile]
    </messageWithProperties>
         <properties>
              <name>Error Code</name>
              <value>0</value>
         </properties>
         <properties>
              <name>ticketId</name>
              <value>1</value>
         </properties>
         <properties>
              <name>fileName</name>
              <value>testFile</value>
         </properties>
         <propertiesAsString>     Error Code=[0]
         ticketId=[1]
         fileName=[testFile]
    </propertiesAsString>
    </ns2:Exception>
    I wanted to parse through it and get the errorCode....
    I am using :-
    xmlObject.load(xmlText : xmlContent);
    xmlMessage = xmlObject.selectString(xpath : "/ns2/errorCode");
    But this doesn't seem to work..
    Any idea?

  • Parsing XML string with XPath

    Hi,-
    I am trying to parse an XML string with xpath as follows but I am getting null for getresult.
    I am getting java.xml.xpath.xpathexpressionexception at line where
    getresult = xpathexpression.evaluate(isource); is executed.
    What should I do after
    xpathexpression = xPath.compile("a/b");in the below snippet?
    Thanks
    String xmlstring ="..."; // a valid XML string;
    Xpath xpath = XPathFactory.newInstance().newPath();
    xpathexpression = xPath.compile("a/b");
    // I guess the following line is not correct
    InputSource isource = new inputSource(new ByteArrayInputStream(xmlstring.getBytes())); right
    getresult = xpathexpression.evaluate(isource);My xml string is like:
    <a>
      <b>
         <result> valid some more tags here
         </result>
      </b>
      <c> 10
      </c>
    </a>Edited by: geoman on Dec 8, 2008 2:30 PM

    I've never used the version of evaluate that takes an InputSource. The difficulty with using it is that it does not save the DOM object. Each expression you evaluate will have to create the DOM object, use it once and then throw it away. I've yet to write a program that only needs one answer from an XML document. Usually, I use XPath to locate somewhere in a document and then read "nearby" content, add new content nearby, delete content, or move content. I'd suggest you may want to parse the XML stream and save the DOM Document.
    Second, all of the XPath expressions search from a "context node". I have not had good luck searching from the Document object, so I always get the root element first. I think the expression should work if you use the root as the context node. You will need one of the versions of evaluate that uses an Object as the parameter.

  • Help: How to parse XML string into Node Context

    Hi Experts,
    I am trying to work with a web dynpro for java application which calls a Web Service. I can call the web service successfully, however I have a problem on interpreting the response result into table. The response result is in (XML) string format, like this:
    I followed this , but it resulted to an error:
    com.sap.engine.lib.xml.parser.NestedSAXParserException: Fatal Error: com.sap.engine.lib.xml.parser.ParserException: Name expected: 0x20(:main:, row:158, col:59)(:main:, row=158, col=59) -> com.sap.engine.lib.xml.parser.ParserException: Name expected: 0x20(:main:, row:158, col:59)
    do anyone of you had a similar experience and were able to resolve it, please post it here. it will be highly appreciated. thanks in advance.

    Try this :
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(new org.xml.sax.InputSource(new StringReader(strXml)));Hope this helps.

  • Xml report getting errored out

    hi friends
    i have one custom xml report with ten parameters whenever i submiteing concurrent program with mandatory paramas it will getting succesfully completed
    without requirement out put. Again whenever i submiteed program with mandatory params and non mandatory parameters it will getting errored out .
    the error was below
    Enter Password:
    MSG-01275: Date select AND afrm.certificate_date BETWEEN :P_FROM_DATE and :P_TO_DATE
    01-OCT-11 31-DEC-11
    REP-1276: Placeholder 'CP_PARENT_NAME' references one or more non-formula columns.
    REP-0069: Internal error
    REP-57054: In-process job terminated:Terminated with error:
    REP-1276: Placeholder 'CP_PARENT_NAME' references one or more non-formula columns.
    thanks
    chandra

    Hi Chandra,
    There might be a problem with your .rdf.
    Please check the formula column and use srw.message functionality to debug.
    And please enable Trace option while you are running the report.
    So that you can get more info about the errors.

  • How to parse xml string

    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)));

  • Passing / parsing XML String IN / OUT from PL / SQL package

    Hello, People !
    I am wondering where can I find exact info (with code sample) about following :
    We use Oracle 8.1.6 and 8.1.7. I need to pass an XML String (could be from VARCHAR2 to CLOB) from VB 6.0 to PL/SQL package. Then I need to use built in PL/SQL XML parser to parse given string (could be large hierarchy of nodes)
    and the return some kind of cursor thru I can loop and insert data into
    different db Tables. (The return value may have complex parent/child data relationship - so I am not sure If this should be a cursor)
    I looked online many site for related info - can't find what I am looking
    for - seems like should be a common question.
    Thanx a lot !

    Hello, People !
    I am wondering where can I find exact info (with code sample) about following :
    We use Oracle 8.1.6 and 8.1.7. I need to pass an XML String (could be from VARCHAR2 to CLOB) from VB 6.0 to PL/SQL package. Then I need to use built in PL/SQL XML parser to parse given string (could be large hierarchy of nodes)
    and the return some kind of cursor thru I can loop and insert data into
    different db Tables. (The return value may have complex parent/child data relationship - so I am not sure If this should be a cursor)
    I looked online many site for related info - can't find what I am looking
    for - seems like should be a common question.
    Thanx a lot !

  • Parse xml string not file

    Hi
    Can anyone help me I am trying to parse a xml file that is in a StringBuffer and not a file.
    Any suggestions would be great.
    Thanks ;>

    You can create a StringReader object from your StringBuffer. Once you have a StringReader object, you can create an InputSource object. Then, you can parse the InputSource with a DocumentBuilder object. I enclosed the code to illustrate. The method printXml is only used to check that the XML string is properly parsed and retrieved.
    import java.io.IOException;
    import java.io.StringReader;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.FactoryConfigurationError;
    import javax.xml.parsers.ParserConfigurationException;
    import org.w3c.dom.Attr;
    import org.w3c.dom.Document;
    import org.w3c.dom.NamedNodeMap;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    public class Parsing
        public static void main(String[] args)
         StringBuffer yourStringBuffer = new StringBuffer("<message>"
                                        +"<header>This is the message's header</header>"
                                        + "<body>This is the message's body</body>"
                                        + "</message>");
         try {
             DocumentBuilderFactory docBuilderFactory = new org.apache.crimson.jaxp.DocumentBuilderFactoryImpl();
             //throws ParserConfigurationException
             DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
             StringReader strReader = new StringReader(yourStringBuffer.toString());
             //throws SAXException, IOException, IllegalArgumentException
             Document doc = docBuilder.parse(new InputSource(strReader));
             System.out.println(printXml(doc)); //check if the XML can be retreived, i.e. it has been parsed successfully
         catch(ParserConfigurationException ex) {
             ex.printStackTrace();        
         catch(SAXException ex) {
             ex.printStackTrace();
         catch(IOException ex) {
             ex.printStackTrace();
         catch(IllegalArgumentException ex) {
             ex.printStackTrace();
        //Convenient method to print a Document object.
        public static String printXml(Document xmlDoc)
         StringBuffer xml = new StringBuffer("************ Xml Document *************");
         print(xmlDoc,xml);
         return xml.toString();
        protected static void print(Node node, StringBuffer strXml)
         int type;
         String elementName;
         Node childNode;
         NamedNodeMap attrs;
         Attr attrib;
         NodeList childNodes;
         strXml.append(System.getProperty("line.separator"));
         if(node == null)
             return;
         type = node.getNodeType();
         switch (type) {
         case Node.DOCUMENT_NODE: {
             print(((Document)node).getDocumentElement(),strXml); //recursive call to browse the tree
             break;
         case Node.ELEMENT_NODE: {
             elementName = node.getNodeName();
             strXml.append("<" + elementName);
             attrs = node.getAttributes();
             if(attrs == null)
              strXml.append(">");
             else {
              for(int i = 0; i < attrs.getLength(); i++) {
                  attrib = (Attr) attrs.item(i);
                  strXml.append(" " + attrib.getName() + "=\"" + attrib.getValue() + "\"");
              strXml.append(">");
             childNodes = node.getChildNodes();
             if(childNodes == null) return;
             for (int i = 0; i <  childNodes.getLength(); i++) {
              childNode = childNodes.item(i);
              if(childNode.getNodeType() == Node.TEXT_NODE)
                  strXml.append(childNode.getNodeValue());
              else
                  print(childNode,strXml);
             strXml.append(System.getProperty("line.separator"));
             strXml.append("</" + elementName + ">");
    }Hope this helps.

  • Parsing xml string does not see the dtd inside jar

    Hello,
    I have problem parsing an XML string because the DTD file is not found (my DTD file is located inside my application's jar file). I am trying to instruct the parser where the DTD is located. If my DTD would have been on the filesystem directlly things would be working just fine, but i need to keep the DTD inside my JAR.
    String dtdLocation = ClassLoader.getSystemResource("mydtd.dtd").toURI().toString();
    Document xmlDocument = builder.parse(new ByteArrayInputStream(xmlFile.getBytes()),dtdLocation);The XML string looks something like this:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE Properties SYSTEM "mydtd.dtd">
    <Properties>
    <Prop>val<Prop>
    </Properties>

    >
    Hi,
    Don't resurrect old threads, and why on earth did you resurrect 5 threads? I'm locking the zombie threads. Create a new thread if you have a specific question.
    Kaj

  • Error while creating DocumentBuilderFactory object for parsing XML string

    When I try to execute the following statement in an EJB class,
    DocumentBuilderFactory df=DocumentBuilderFactory.newInstance();
    I get the following exception:
    javax.xml.parsers.FactoryConfigurationError: Provider org.apache.crimson.jaxp.DocumentBuilderFactoryImpl not found
    When the same statement is executed from a standalone java class, it works fine.
    The IDE used is Visual Age for Java.
    The JAXP package used is JAXP 1.0.1
    Can anybody please let me know how can we overcome this problem?
    Thanks and Regards,
    Shashi Anand B
    E-Mail : [email protected]

    javax.xml.parsers.FactoryConfigurationError: Provider
    org.apache.crimson.jaxp.DocumentBuilderFactoryImpl not
    foundI suspect that this may be due to a classpath issue and/or a Java version issue. Doe your Visual Age installation use Java 1.3? Do you have Sun Java 1.4 also installed on your system? It may be that when you are executing from a standalone Java class, that you are using the Java 1.4 runtime, which include the org.apach.crimson.* classes. Earlier version of Java do not include this, although it may be in the JAXP package.
    I think that your Visual Age IDE is configured such that the DocumentBuilderFactory is unable to find the appropriate implementation.
    I hope this helps!
    - David

  • How to parse xml string using JSTL

    Suppose this is my string:-----
    <books>
    <book>
    <title id=1>Book Title A</title>
    <author>A. B. C.</author>
    <price>17.95</price>
    </book>
    <book>
    <title id=2>Book Title B</title>
    <author>X. Y. Z.</author>
    <price>24.99</price>
    </book>
    </books>
    and I want to read title id = 1 then, how to parse it, I found tutorials regarding parsing simple xml document but how to parse attributes of a given XML

    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)));

Maybe you are looking for

  • Database Restoration

    Hello  ,         My Question is i have taken a backup of database from sql server 2012 and i trying to restore on sqlserver 2008 it's showing me error. I know why its giving me error. But  i want know is there any solution for this problem or is ther

  • Where to find Win XP drivers for Portege R400

    I need help. Cannot work on Vista - so want to downgrade to WXP. But there are no drivers on official Toshiba site for this OS only for Vista. I cannot find info about compatibility of Toshiba software (that works on Vista) with XP. Can you help me a

  • CUCM 9.1 last login message error

    Hi, i am coming across an issue wehre AD user try to login CUCM admin and sees incorrect last logiin message. It shows last login from 1 Jan 1970. But if ccmadmin login it shows correct date and time for last login. attached are screenshots.   Not su

  • Po without GL account.

    Dear Friends,                        My purchase department is creating PO with material master. Sometime they are creating PO with material for whom GL account is not attached.They are not checking PO for GL account i.e.GL account is coming or not ?

  • New iPhone 4S doesn't sync all SMS messages

    I got the new iPhone 4S yesterday and I immediately moved over my SIM card from my old iPhone 4 onto there. I synched everything including messages, notes, calendars, emails and such fine, except it only synced to October 13. It's November 8 as of no