Problem parsing a xml using Jdom

Hi all,
I am reposting it as I was told to format the code and send it again.
I am trying to parse a xml file using a jdom java code.This code works fine if I remove xmlns attribute in the root element. (I get the expected result) .If the "xmlns" attribute is put in the xml as it should be then the parsing and retrieving returns null. Please tell me how to fix this issue.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Xml
<process name="CreateKBEntryService" targetNamespace="http://serena.com/CreateKBEntryService" suppressJoinFailure="yes" xmlns:tns="http://serena.com/CreateKBEntryService" xmlns="http://schemas.xmlsoap.org/ws/2003/03/business-process/" xmlns:bpelx="http://schemas.oracle.com/bpel/extension" xmlns:ora="http://schemas.oracle.com/xpath/extension" xmlns:nsxml0="http://localhost:8080/axis/services/CreateKBEntryService" xmlns:nsxml1="http://DefaultNamespace" xmlns:bpws="http://schemas.xmlsoap.org/ws/2003/03/business-process/">
<partnerLinks>
<partnerLink name="client" partnerLinkType="tns:CreateKBEntryService" myRole="CreateKBEntryServiceProvider"/>
<partnerLink name="CreateKBEntryPartnerLink" partnerLinkType="nsxml0:CreateKBEntryLink" partnerRole="CreateKBEntryProvider"/>
</partnerLinks>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`
Java:
import java.io.*;
import java.util.*;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
public class sample1 {
public static void main(String[] args) throws Exception {
// create a XML parser and read the XML file
SAXBuilder oBuilder = new SAXBuilder();
Document oDoc = oBuilder.build(new File("**xml file location**"));
Element root = oDoc.getRootElement();
System.out.println(root.getName());
String tgtns= root.getAttributeValue("targetNamespace");
System.out.println("tgt ns "+ tgtns);
List list= root.getChildren("partnerLinks");
Iterator it1= list.iterator();
System.out.println("Iterator 1 - "+list.size());
while(it1.hasNext()){
Element partnerlinks = (Element)it1.next();
List list2= partnerlinks.getChildren("partnerLink");
System.out.println("iterator 2 - "+list2.size());
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Result:
Without Xmlns in xml file(Expected and correct output)
process
tgt ns http://serena.com/CreateKBEntryService
Iterator 1 - 1//expected and correct result that comes when I remove xmlns attribute from xml
iterator 2 - 2
Result with xmlns:
process
tgt ns http://serena.com/CreateKBEntryService
Iterator 1 - 0 //instead of 0 should return 1

One suggestion to try:
Change your code to the following
Element root = oDoc.getRootElement();
System.out.println(root.getName());
String tgtns= root.getAttributeValue("targetNamespace");
System.out.println("tgt ns "+ tgtns);
Namespace ns = Namespace.getNamespace(
  "http://schemas.xmlsoap.org/ws/2003/03/business-process/" );
List list= root.getChildren("partnerLinks", ns );
Iterator it1= list.iterator();
System.out.println("Iterator 1 - "+list.size());The JavaDoc says for the one-arg getChildren()
If this target element has no nested elements with the given name outside a namespace, an empty List is returned.
Your elements have a namespace (the default one) so it should be worth a try.
Dave Patterson

Similar Messages

  • Parsing a XML using Jdom --- Problem pls help

    Hi all,
    I am reposting it as I was told to format the code and send it again.
    I am trying to parse a xml file using a jdom java code.This code works fine if I remove xmlns attribute in the root element. (I get the expected result) .If the "xmlns" attribute is put in the xml as it should be then the parsing and retrieving returns null. Please tell me how to fix this issue.
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Xml
    <process name="CreateKBEntryService" targetNamespace="http://serena.com/CreateKBEntryService" suppressJoinFailure="yes" xmlns:tns="http://serena.com/CreateKBEntryService" xmlns="http://schemas.xmlsoap.org/ws/2003/03/business-process/" xmlns:bpelx="http://schemas.oracle.com/bpel/extension" xmlns:ora="http://schemas.oracle.com/xpath/extension" xmlns:nsxml0="http://localhost:8080/axis/services/CreateKBEntryService" xmlns:nsxml1="http://DefaultNamespace" xmlns:bpws="http://schemas.xmlsoap.org/ws/2003/03/business-process/">
    <partnerLinks>
    <partnerLink name="client" partnerLinkType="tns:CreateKBEntryService" myRole="CreateKBEntryServiceProvider"/>
    <partnerLink name="CreateKBEntryPartnerLink" partnerLinkType="nsxml0:CreateKBEntryLink" partnerRole="CreateKBEntryProvider"/>
    </partnerLinks>
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`
    Java:
    import java.io.*;
    import java.util.*;
    import org.jdom.Document;
    import org.jdom.Element;
    import org.jdom.input.SAXBuilder;
    public class sample1 {
    public static void main(String[] args) throws Exception {
    // create a XML parser and read the XML file
    SAXBuilder oBuilder = new SAXBuilder();
    Document oDoc = oBuilder.build(new File("**xml file location**"));
    Element root = oDoc.getRootElement();
    System.out.println(root.getName());
    String tgtns= root.getAttributeValue("targetNamespace");
    System.out.println("tgt ns "+ tgtns);
    List list= root.getChildren("partnerLinks");
    Iterator it1= list.iterator();
    System.out.println("Iterator 1 - "+list.size());
    while(it1.hasNext()){
    Element partnerlinks = (Element)it1.next();
    List list2= partnerlinks.getChildren("partnerLink");
    System.out.println("iterator 2 - "+list2.size());
    }~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Result:
    Without Xmlns in xml file(Expected and correct output)
    process
    tgt ns http://serena.com/CreateKBEntryService
    Iterator 1 - 1//expected and correct result that comes when I remove xmlns attribute from xml
    iterator 2 - 2
    Result with xmlns:
    process
    tgt ns http://serena.com/CreateKBEntryService
    Iterator 1 - 0 //instead of 0 should return 1

    One suggestion to try:
    Change your code to the following
    Element root = oDoc.getRootElement();
    System.out.println(root.getName());
    String tgtns= root.getAttributeValue("targetNamespace");
    System.out.println("tgt ns "+ tgtns);
    Namespace ns = Namespace.getNamespace(
      "http://schemas.xmlsoap.org/ws/2003/03/business-process/" );
    List list= root.getChildren("partnerLinks", ns );
    Iterator it1= list.iterator();
    System.out.println("Iterator 1 - "+list.size());The JavaDoc says for the one-arg getChildren()
    If this target element has no nested elements with the given name outside a namespace, an empty List is returned.
    Your elements have a namespace (the default one) so it should be worth a try.
    Dave Patterson

  • Problem in parsing an XML using SAX parser

    Hai All,
    I have got a problem in parsing an XML using SAX parser.
    I have an XML (sample below) which need to be parsed
    <line-items>
    <item num="1">
         <part-number>PN1234</part-number>
         <quantity uom="ea">10</quantity>
         <lpn>LPN1060</lpn>
         <reference num="1">Line ref 1</reference>
         <reference num="2">Line ref 2</reference>
         <reference num="3">Line ref 3</reference>
    </item>
    <item num="2">
         <part-number>PN1527</part-number>
         <quantity uom="lbs">5</quantity>
         <lpn>LPN2152</lpn>
         <reference num="1">Line ref 1</reference>
         <reference num="2">Line ref 2</reference>
         <reference num="3">Line ref 3</reference>
    </item>
    <item num="n">
    </item>
    </line-items>
    There can be any number of items( 1 to n). I need to parse these
    item values using SAX parser and invoke a stored procedure for
    each item with its
    values(partnumber,qty,lpn,refnum1,refnum2,refnum3).
    Suppose if there are 100 items, i need to invoke the stored
    procedure sp1() 100 times for each item.
    I need to invoke the stored procedure in endDocument() method of
    SAX event handler and not in endelement() method.
    What is the best way to store those values and invoke the stored
    procedure in enddocument() method.
    Any help would br greatly appreciated.
    Thanks in advance
    Pooja.

    VO or ValueObject is a trendy new name for Beans.
    So just create an item class with variables for each of the sub elements.
    <item>
    <part-number>PN1234</part-number>
    <quantity uom="ea">10</quantity>
    <lpn>LPN1060</lpn>
    <reference num="1">Line ref 1</reference>
    <reference num="2">Line ref 2</reference>
    <reference num="3">Line ref 3</reference>
    </item>
    public class ItemVO
    String partNumber;
    int quantity;
    String quantityType;
    String lpn;
    List references = new ArrayList();
    * @return Returns the lpn.
    public String getLpn()
    return this.lpn;
    * @param lpn The lpn to set.
    public void setLpn(String lpn)
    this.lpn = lpn;
    * @return Returns the partNumber.
    public String getPartNumber()
    return this.partNumber;
    * @param partNumber The partNumber to set.
    public void setPartNumber(String partNumber)
    this.partNumber = partNumber;
    * @return Returns the quantity.
    public int getQuantity()
    return this.quantity;
    * @param quantity The quantity to set.
    public void setQuantity(int quantity)
    this.quantity = quantity;
    * @return Returns the quantityType.
    public String getQuantityType()
    return this.quantityType;
    * @param quantityType The quantityType to set.
    public void setQuantityType(String quantityType)
    this.quantityType = quantityType;
    * @return Returns the references.
    public List getReferences()
    return this.references;
    * @param references The references to set.
    public void setReferences(List references)
    this.references = references;

  • Parsing an XML using DOM parser in Java in Recursive fashion

    I need to parse an XML using DOM parser in Java. New tags can be added to the XML in future. Code should be written in such a way that even with new tags added there should not be any code change. I felt that parsing the XML recursively can solve this problem. Can any one please share sample Java code that parses XML recursively. Thanks in Advance.

    Actually, if you are planning to use DOM then you will be doing that task after you parse the data. But anyway, have you read any tutorials or books about how to process XML in Java? If not, my suggestion would be to start by doing that. You cannot learn that by fishing on forums. Try this one for example:
    http://www.cafeconleche.org/books/xmljava/chapters/index.html

  • Issue in parsing an XML using kxml in Creme 4.1 JVM for WIndows CE

    Hi,
    I have written a code to parse an XML using KXML.jar.
    The code will read the XML file, parse the content and writes data to a text file.
    The code is working fine in normal Windows XP enviroment.
    The same code when tested in a pocket PC is not writing the content and also not throwing any error or exception.
    Please give me some inputs on how to resove this issue.
    TIA,
    shubakarthik

    Hi,
    I have written a code to parse an XML using KXML.jar.
    The code will read the XML file, parse the content and writes data to a text file.
    The code is working fine in normal Windows XP enviroment.
    The same code when tested in a pocket PC is not writing the content and also not throwing any error or exception.
    Please give me some inputs on how to resove this issue.
    TIA,
    shubakarthik

  • Parsing Xml using Jdom

    Hi all,
    I am reposting it as I was told to format the code and send it again.
    I am trying to parse a xml file using a jdom java code.This code works fine if I remove xmlns attribute in the root element. (I get the expected result) .If the "xmlns" attribute is put in the xml as it should be then the parsing and retrieving returns null. Please tell me how to fix this issue.
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Xml
    <process name="CreateKBEntryService" targetNamespace="http://serena.com/CreateKBEntryService" suppressJoinFailure="yes" xmlns:tns="http://serena.com/CreateKBEntryService" xmlns="http://schemas.xmlsoap.org/ws/2003/03/business-process/" xmlns:bpelx="http://schemas.oracle.com/bpel/extension" xmlns:ora="http://schemas.oracle.com/xpath/extension" xmlns:nsxml0="http://localhost:8080/axis/services/CreateKBEntryService" xmlns:nsxml1="http://DefaultNamespace" xmlns:bpws="http://schemas.xmlsoap.org/ws/2003/03/business-process/">
    <partnerLinks>
    <partnerLink name="client" partnerLinkType="tns:CreateKBEntryService" myRole="CreateKBEntryServiceProvider"/>
    <partnerLink name="CreateKBEntryPartnerLink" partnerLinkType="nsxml0:CreateKBEntryLink" partnerRole="CreateKBEntryProvider"/>
    </partnerLinks>
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`
    Java:
    import java.io.*;
    import java.util.*;
    import org.jdom.Document;
    import org.jdom.Element;
    import org.jdom.input.SAXBuilder;
    public class sample1 {
    public static void main(String[] args) throws Exception {
    // create a XML parser and read the XML file
    SAXBuilder oBuilder = new SAXBuilder();
    Document oDoc = oBuilder.build(new File("**xml file location**"));
    Element root = oDoc.getRootElement();
    System.out.println(root.getName());
    String tgtns= root.getAttributeValue("targetNamespace");
    System.out.println("tgt ns "+ tgtns);
    List list= root.getChildren("partnerLinks");
    Iterator it1= list.iterator();
    System.out.println("Iterator 1 - "+list.size());
    while(it1.hasNext()){
    Element partnerlinks = (Element)it1.next();
    List list2= partnerlinks.getChildren("partnerLink");
    System.out.println("iterator 2 - "+list2.size());
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Result:
    Without Xmlns in xml file(Expected and correct output)
    process
    tgt ns http://serena.com/CreateKBEntryService
    Iterator 1 - 1//expected and correct result that comes when I remove xmlns attribute from xml
    iterator 2 - 2
    Result with xmlns:
    process
    tgt ns http://serena.com/CreateKBEntryService
    Iterator 1 - 0 //instead of 0 should return 1

    Hi all,
    I am reposting it as I was told to format the code and send it again.
    I am trying to parse a xml file using a jdom java code.This code works fine if I remove xmlns attribute in the root element. (I get the expected result) .If the "xmlns" attribute is put in the xml as it should be then the parsing and retrieving returns null. Please tell me how to fix this issue.
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Xml
    <process name="CreateKBEntryService" targetNamespace="http://serena.com/CreateKBEntryService" suppressJoinFailure="yes" xmlns:tns="http://serena.com/CreateKBEntryService" xmlns="http://schemas.xmlsoap.org/ws/2003/03/business-process/" xmlns:bpelx="http://schemas.oracle.com/bpel/extension" xmlns:ora="http://schemas.oracle.com/xpath/extension" xmlns:nsxml0="http://localhost:8080/axis/services/CreateKBEntryService" xmlns:nsxml1="http://DefaultNamespace" xmlns:bpws="http://schemas.xmlsoap.org/ws/2003/03/business-process/">
    <partnerLinks>
    <partnerLink name="client" partnerLinkType="tns:CreateKBEntryService" myRole="CreateKBEntryServiceProvider"/>
    <partnerLink name="CreateKBEntryPartnerLink" partnerLinkType="nsxml0:CreateKBEntryLink" partnerRole="CreateKBEntryProvider"/>
    </partnerLinks>
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`
    Java:
    import java.io.*;
    import java.util.*;
    import org.jdom.Document;
    import org.jdom.Element;
    import org.jdom.input.SAXBuilder;
    public class sample1 {
    public static void main(String[] args) throws Exception {
    // create a XML parser and read the XML file
    SAXBuilder oBuilder = new SAXBuilder();
    Document oDoc = oBuilder.build(new File("**xml file location**"));
    Element root = oDoc.getRootElement();
    System.out.println(root.getName());
    String tgtns= root.getAttributeValue("targetNamespace");
    System.out.println("tgt ns "+ tgtns);
    List list= root.getChildren("partnerLinks");
    Iterator it1= list.iterator();
    System.out.println("Iterator 1 - "+list.size());
    while(it1.hasNext()){
    Element partnerlinks = (Element)it1.next();
    List list2= partnerlinks.getChildren("partnerLink");
    System.out.println("iterator 2 - "+list2.size());
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Result:
    Without Xmlns in xml file(Expected and correct output)
    process
    tgt ns http://serena.com/CreateKBEntryService
    Iterator 1 - 1//expected and correct result that comes when I remove xmlns attribute from xml
    iterator 2 - 2
    Result with xmlns:
    process
    tgt ns http://serena.com/CreateKBEntryService
    Iterator 1 - 0 //instead of 0 should return 1

  • Problem in parsing an xml using DOM parser.

    Hi,
        I have created an action block for client.
        it  takes a xml file present on D drive and generates a pdf by parsing the xml file.
        My code was working perfectly fine till yesterday.
    But now i getting , [INFO ]: Error-- Premature end of file.  org.xml.sax.SAXParseException: Premature end of file.
    But xml is perfectly fine. Also the code work from eclipse.
    Need some inputs on this.
    Regards,
    Vishal Jadhav
    Edited by: vishal jadhav on Jan 23, 2009 9:49 AM

    Vishal,
    what exactly did you change? How do you call the action block? What version/Support package/Build of MII do you use?
    Have you see the following thread? There a user had the same message which was caused by missing credentials.
    [https://forums.sdn.sap.com/click.jspa?searchID=21364701&messageID=6756453]
    Michael
    Edited by: Michael Otto on Jan 23, 2009 11:57 AM

  • Parse into array using JDOM! please help

    hey,
    i've managed to parse an xml document using JDOM
    i[b] need to be able to parse it and store the text (the value of each node) into an array, and then insert into db etc.
    the problem is with the recursive function listChildren which calls itself... can someone tell me where do i insert the block of code such that i can store it into an array of string.
    here's the code:
    public static void parse(String stock) throws SQLException
    SAXBuilder builder = new SAXBuilder();
    Reader r = new StringReader(stock);
    Document doc = builder.build(r);
    Element root = doc.getRootElement();
    listChildren(root, 0);
    public static void listChildren(Element current, int depth) throws Exception
    String nodes = current.getName();
    System.out.println(nodes + " : " + current.getText());
    List children = current.getChildren();
    Iterator iterator = children.iterator();
    while(iterator.hasNext())
    Element child = (Element) iterator.next();
    listChildren(child, depth+1);
    i'm looking for something like:
    a=current.getText();
    but i donno where to include this line of code, please help
    cheers,
    Shivek Sachdev

    hi, I suggest you make an array of byte arrays
    --> Byte[][] and use one row for each number
    you can do 2 things,
    take each cipher of one number and put one by one in each column of the row correspondent to that number. of course it may take too much room if the int[] is too big, but that is the easiest way I think
    the other way is dividing your number into bitsets(class BitSet) with sizes of 8 bits and then you can save each bit into each column of your array. and you still have one number in each row. To put your numbers back use the same class.
    Maybe someone has an easier way, I couldnt think of any.

  • Problems parsing a XML with binary element

    Hi,
    I'm trying to parse a xml that contains an element with the type "xs:hexBinary".
    The problem is that when i load a file in to the xml everything goes fine ...
    no matter the size of the file (i've tested it with 6Mb file), the problem is
    that when i try to parse it i got an error "java.lang.OutOfMemoryError" ... i
    don't know if there is any kind of size restriction or something like that.
    Any information would be gratefully considered.
    Thanks a lot.
    Rober.

    XML is a text format so of course it can't include binary data such as GIFs. But then so is HTML, so there doesn't seem to be much point in doing this. Your HTML would have to include a link to the GIF, rather than the GIF itself in any format, binary or otherwise. And therefore so should the XML. Given all that, it follows that parsers don't deal with whatever it is you are attempting.

  • How to edit xml using jdom

    hi
    how to read and edit xml file using jdom, i tried using
    javax.xml.transform.*; // JAXP
    javax.xml.transform.dom.DOMSource; //
    i can read xml file . but iam not able to edit the xml file.
    how to achive this

    1. Select nodes to be modified with the JDom XPath class selectSingleNode and selectNodes methods.
    SAXBuilder saxBuilder=new SAXBuilder("org.apache.xerces.parsers.SAXParser");
    org.jdom.Document jdomDocument=saxBuilder.build(new File("c:/input.xml"));
    org.jdom.Element node= (org.jdom.Element)(XPath.selectSingleNode(jdomDocument,"/root/node"));
    2. Modify the node values with the Element class setter methods.
    3. Output document with the XMLOutputer class.

  • Hot to parse XML using JDOM?

    <Case caseID="1808977179">
    <attr name="create_time">2003-12-04 16:42:19.0</attr>
    <attr name="name">1KEEJCE</attr>
    <attr name="owner_id">2yawpgx5vhpus</attr>
    <attr name="expected_closure">2003-12-04 16:42:19.0</attr>
    <attr name="subject">test tech support case</attr>
    </Case>
    obviously my attribute name (which is also named as "name") is the same for all my five entries. How can I parse all of them?I can only parse the first entry.

    this is the comp xml file:
    <GetUserCasesResponse>
         <Case caseID="1808977179">
         <attr name="name">1KEEJCE</attr>
         <attr name="create_time">2003-12-04 16:42:19.0</attr>     
         <attr name="owner_id">2yawpgx5vhpus</attr>
         <attr name="expected_closure">2003-12-04 16:42:19.0</attr>
         <attr name="subject">test tech support case</attr>
         </Case>
         <Case caseID="1326717944">
         <attr name="name">2DC65T5</attr>
         <attr name="create_time">2003-12-04 16:46:02.0</attr>
         <attr name="owner_id">2yawpgx5vhpus</attr>
         <attr name="expected_closure"></attr>
         <attr name="subject">test tech support case</attr>
         </Case>
         <Case caseID="1489179651"><attr name="name">16ZUFEZ</attr>
         <attr name="create_time">2003-12-04 16:48:15.0</attr>
         <attr name="owner_id"></attr>
         <attr name="expected_closure">2003-12-04 16:48:15.0</attr>
         <attr name="subject">test tech support case</attr>
         </Case>
         <Case caseID="1145690438"><attr name="name">2Y3XDR7</attr>
         <attr name="create_time">2003-12-04 16:56:17.0</attr>
         <attr name="owner_id">2yawpgx5vhpus</attr>
         <attr name="expected_closure">2003-12-04 16:56:17.0</attr>
         <attr name="subject">testing</attr>
         </Case>
         <Case caseID="1145690438"><attr name="name">2Y3XDR7</attr>
         <attr name="create_time">2003-12-04 16:56:17.0</attr>
         <attr name="owner_id">2yawpgx5vhpus</attr>
         <attr name="expected_closure">2003-12-04 16:56:17.0</attr>
         <attr name="subject">testing</attr>
         </Case>
    </GetUserCasesResponse>
    this is my code:
         public static void readXML( )
              try
                   SAXBuilder builder = new SAXBuilder( false );
                   Document doc = builder.build( new File(filenameConstant ) );
                   Element root = doc.getRootElement();
                   List listCase = root.getChildren("Case");
                   Iterator iterateCase = listCase.iterator();
                   while(iterateCase.hasNext())
                        Element attr = (Element) iterateCase.next();
                        System.out.println("" + attr.getChild("attr").getText() );
              catch( Exception e)
                   e.printStackTrace();
    This is my output:
    1KEEJCE
    2DC65T5
    16ZUFEZ
    2Y3XDR7
    2Y3XDR7
    Press any key to continue...
    Obviously I can only get the first element (<attr name="name">1KEEJCE</attr>
    ) of each cases,how can I get the other four given that they have the same attribute name ( which is named "name" ).

  • Problem parsing an XML

    I have this servlet that should be parsing a string received using a HTTP POST, here is the code of the servlet:
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.FactoryConfigurationError;
    import javax.xml.parsers.ParserConfigurationException;
    import org.xml.sax.InputSource;
    import org.w3c.dom.*;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    import org.apache.xml.serialize.*;
    import org.xml.sax.InputSource;
    public class SMSReceiver extends HttpServlet
    public void service(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException
    try {
    //Initialization for the servlet
    ServletInputStream entrada = req.getInputStream();
    ServletOutputStream salida = res.getOutputStream();
    //Reading of the entering string
    BufferedReader lector = new BufferedReader(new InputStreamReader (entrada));
    res.setContentType("text/HTML");
    try {
    DocumentBuilderFactory factory =
    DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    InputSource inStream = new InputSource();
    inStream.setCharacterStream(new StringReader(lector.readLine()));
    Document doc1 = builder.parse(inStream);
    NodeList listasms = doc1.getElementsByTagName("sms");
    for(int s=0; s<listasms.getLength() ; s++)
    Node nodosms = listasms.item(s);
    if(nodosms.getNodeType() == Node.ELEMENT_NODE)
    Element elementosms = (Element)nodosms;
    NodeList listatelf = elementosms.getElementsByTagName("tlf");
    Element elementotelf = (Element)listatelf.item(0);
    NodeList textTelfList = elementotelf.getChildNodes();
    String telefono = ((Node)textTelfList.item(0)).getNodeValue();
    salida.println("Telefono" + telefono);
    NodeList listaop = elementosms.getElementsByTagName("op");
    Element elementoop = (Element)listaop.item(0);
    NodeList textOpList = elementoop.getChildNodes();
    String operadora = ((Node)textOpList.item(0)).getNodeValue();
    NodeList listasc = elementosms.getElementsByTagName("sc");
    Element elementosc = (Element)listasc.item(0);
    NodeList textSCList = elementosc.getChildNodes();
    String shortcode = ((Node)textSCList.item(0)).getNodeValue();
    NodeList listabody = elementosms.getElementsByTagName("body");
    Element elementobody = (Element)listabody.item(0);
    NodeList textBodyList = elementobody.getChildNodes();
    String body = ((Node)textBodyList.item(0)).getNodeValue();
    catch (SAXParseException err)
    salida.println ("** Parsing error" + ", line " + err.getLineNumber () + ", uri " + err.getSystemId ());
    salida.println(" " + err.getMessage ());
    catch (SAXException e)
    Exception x = e.getException ();
    ((x == null) ? e : x).printStackTrace ();
    catch (Throwable t)
    t.printStackTrace ();
    The error I get from the servlet is:
    ** Parsing error, line 1, uri null
    XML document structures must start and end within the same entity.
    Finished executing
    Here's the code of the program that sends the HTTP POST:
    import java.io.*;
    import java.net.*;
    import java.io.*;
    public class HTTPSender {
    public static void main(String[] args) throws Exception {
    try {
    String cadena = ""
    + "<root>\n"
    + "<sms>\n"
    + "<tlf>" + (URLEncoder.encode("4123161640" , "UTF-8")) + "</tlf>\n"
    + "<op>" + (URLEncoder.encode("D" , "UTF-8")) + "</op>\n"
    + "<sc>" + (URLEncoder.encode("0000" , "UTF-8")) + "</sc>\n"
    + "<body>" + (URLEncoder.encode("PRUEBA DE MENSAJE MOVIL+" , "UTF-8")) + "</body>\n"
    + "</sms>\n"
    + "</root>";
    //URL url = new URL("http://200.74.214.222:8080/MovilPlus/MovilPlusResponse");
    URL url = new URL("http://localhost:8080/SMSconnector/SMSReceiver");
    int i = 0;
    while (i!=1) {
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(cadena);
    wr.flush();
    // Get the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null) {
    System.out.println(line);
    wr.close();
    rd.close();
    i = i + 1;}
    } catch (Exception e) {
    Now anybody could tell me WHAT I'M DOING WRONG???? Please, need real help here. I'm JAVA newbie but in desperation. Thanks!

    Yes, that's the problem kcounsel, thanks for your help, now I'm parsing I modified my code to store the data into a DATABASE, the problem is that it's not storing and neither giving me any exception for the DB, here's the code to see if you can manage something here:
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.BufferedReader;
    import java.io.FileWriter;
    import java.io.PrintWriter;
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.FactoryConfigurationError;
    import javax.xml.parsers.ParserConfigurationException;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    import org.w3c.dom.*;
    import org.apache.xml.serialize.*;
    import java.net.URLDecoder;
    import java.sql.*;
    import org.xml.sax.InputSource;
    import java.io.StringReader;
    * This class is made as a servlet for receiving strings and saving
    * them as DB records and XML files, it will save each sms in a different XML
    * generating the automatic number of the SMS.
    * <p>Bugs: (None untill now, please notify if you find one)
    * @author (Helder Martins ([email protected]))
    public class SMSReceiver extends HttpServlet
    //Public variables we will need
    public String Stringid;
    public String Stringpath;
    public String st;
    public int nid;
    //Servlet service method, which permits listening of events
    public void service(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException
    //Initialization for the servlet
    ServletOutputStream salida = res.getOutputStream();
    ServletInputStream entrada = req.getInputStream();
    try {
    //Reading of the entering string
    BufferedReader lector = new BufferedReader(new InputStreamReader (entrada));
    res.setContentType("text/HTML");
    //Database handler
    Class.forName("org.gjt.mm.mysql.Driver");
    Connection Conn = DriverManager.getConnection ("jdbc:mysql://localhost:3306/smsdb","root", "");
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    InputSource inStream = new InputSource(entrada);
    Document doc1 = builder.parse(inStream);
    NodeList listasms = doc1.getElementsByTagName("sms");
    for(int s=0; s<listasms.getLength() ; s++)
    Node nodosms = listasms.item(s);
    if(nodosms.getNodeType() == Node.ELEMENT_NODE)
    Element elementosms = (Element)nodosms;
    NodeList listatelf = elementosms.getElementsByTagName("tlf");
    Element elementotelf = (Element)listatelf.item(0);
    NodeList textTelfList = elementotelf.getChildNodes();
    String telefono = ((Node)textTelfList.item(0)).getNodeValue();
    //String SendingAddress = ((Node)textAddressList.item(0)).getNodeValue().trim();
    salida.println("Telefono " + telefono);
    NodeList listaop = elementosms.getElementsByTagName("op");
    Element elementoop = (Element)listaop.item(0);
    NodeList textOpList = elementoop.getChildNodes();
    String operadora = ((Node)textOpList.item(0)).getNodeValue();
    salida.println("Operadora " + operadora);
    NodeList listasc = elementosms.getElementsByTagName("sc");
    Element elementosc = (Element)listasc.item(0);
    NodeList textSCList = elementosc.getChildNodes();
    String shortcode = ((Node)textSCList.item(0)).getNodeValue();
    salida.println("Shortcode " + shortcode);
    NodeList listabody = elementosms.getElementsByTagName("body");
    Element elementobody = (Element)listabody.item(0);
    NodeList textBodyList = elementobody.getChildNodes();
    String body = ((Node)textBodyList.item(0)).getNodeValue();
    salida.println("Body " + body);
    Statement sta = Conn.createStatement();
    sta.executeUpdate("INSERT INTO smstable (telf,op,sc,body) VALUES ('" + telefono + "','" + operadora + "','" + shortcode + "','" + body + "')");
    Conn.commit();
    Conn.close();
    //Catching errors for the SAX and XML parsing
    catch (SAXParseException err)
    salida.println ("** Parsing error" + ", line " + err.getLineNumber () + ", uri " + err.getSystemId ());
    salida.println(" " + err.getMessage ());
    catch (SAXException e)
    Exception x = e.getException ();
    ((x == null) ? e : x).printStackTrace ();
    catch (Throwable t)
    t.printStackTrace ();

  • Parsing my xml using XMLBeans

    I'm trying to use XMLBeans to load my xml file and access different elements of it. Here is my schema:
    <?xml version="1.0" encoding="utf-8"?>
    <xs:schema targetNamespace="http://testing.jsm.jtsd.com/testData"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    elementFormDefault="qualified">
    <xs:element name="Hazard">
    <xs:complexType>
    <xs:sequence>
    <xs:element name="Type" type="xs:string"/>
    <xs:element name="Name" type="xs:string"/>
    <xs:element name="LatLonLocation" type="xs:string"/>
    <xs:element name="ZuluTime" type="xs:string"/>
    <xs:element name="Agent" type="xs:string"/>
    <xs:element name="Munition" type="xs:string"/>
    <xs:element name="DeliveryMethod" type="xs:string"/>
    <xs:element name="DispersalDevice" type="xs:int"/>
    <xs:element name="TypeMatl" type="xs:string"/>
    <xs:element name="MatlForm" type="xs:string"/>
    <xs:element name="TypeMatlAmt" type="xs:int"/>
    <xs:element name="MatlMass" type="xs:double"/>
    </xs:sequence>
    </xs:complexType>
    </xs:element>
    </xs:schema>
    Here is my xml file:
    <Hazard xmlns="http://testing.jsm.jtsd.com/testData">
    <Type>TestHazard</Type>
    <Name>Test_default</Name>
    <LatLonLocation>20 N 20 E</LatLonLocation>
    <ZuluTime>180200ZOCT2007</ZuluTime>
    <Agent>GB</Agent>
    <Munition>500 kg Bomb</Munition>
    <DeliveryMethod>4 AC * 8 Bombs</DeliveryMethod>
    </Hazard>
    I can run scomp and generate a xmlbeans jar file.
    When I try to load my xml file, I get this error:
    org.apache.xmlbeans.XmlException: error: Unexpected element: CDATA
    Here is my java code that tries to load my xml file and errors out:
    HazardDocument myParsedDoc =
    HazardDocument.Factory.parse(myXmlFile);
    Please let me know what I'm doing wrong.

    Thanks for the reply. And sorry for the confusion. I am passing a File to that method call. I've been working on this for awhile and I'm about to go back to JaxB.
    My xsd snippet looks like this now:
    <?xml version="1.0" encoding="utf-8"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://testing.jsm.jtsd.com">
    <xs:element name="JSMData">
    <xs:complexType>
    <xs:sequence>
    <xs:element name="Hazard" minOccurs="0" maxOccurs="unbounded">
    <xs:complexType>
    <xs:sequence>
    <xs:element name="Type" type="xs:string"/>
    <xs:element name="Name" type="xs:string"/>
    I"m able to System out the JSMDataDocument and JSMData after my xml file gets parsed and I can see my xml printed out correctly, but when I do JSMData.sizeOfHazardArray , I get 0 when I should be getting 5 (1 for each Hazard element in my xml file).
    Here is my xml file snippet:
    <JSMData xmlns="http://testing.jsm.jtsd.com">
    <Hazard>
    <Type>RaWnHazard</Type>
    <Name>RW_large_foo</Name>
    Anything wrong here?

  • REMOVING BLANK SPACE IN XML USING JDOM

    <?xml version="1.0" encoding="UTF-8"?>
    <Person >
    <Employee1>
    </Employee1>
    <Employee2>
    </Employee2>
    <Employee3>
    </Employee3>
    </Person>
    I want to remove <Employee2>
              </Employee2>
    and my output should look like this
    <Person >
    <Employee1>
    </Employee1>
    <Employee3>
    </Employee3>
    </Person>
    so i have written code
    import org.jdom.Document;
    import org.jdom.Element;
    import org.jdom.JDOMException;
    import org.jdom.input.SAXBuilder;
    String str = "C://Employee.xml"
    SAXBuilder builder = new SAXBuilder();
    document = builder.build(str);
    Element root = document.getRootElement();
    Element employeeChild1 = root.getChild("Employee1");
    Element employeeChild2 = root.getChild("Employee2");
    employeeChild1.getParent().removeContent(employeeChild1);
    employeeChild2.getParent().removeContent(employeeChild2);
    File file = new File( fileName );
    fos = new FileOutputStream( file );
    Format format = Format.getRawFormat();
    format.setOmitDeclaration(false);
    format.setTextMode(Format.TextMode.PRESERVE);
    outp = new XMLOutputter( format );
    outp.escapeElementEntities(" ");
    outp.output( document, fos );
    fos.flush();
    when i run this code my output comes like this in editplus
    <Person >
    <Employee1>
    </Employee1>
    <Employee3>
    </Employee3>
    </Person>
    and in internet explorer it shows correct
    <Person >
    <Employee1>
    </Employee1>
    <Employee3>
    </Employee3>
    </Person>
    i want to know how can i delete that blank line also because internet explorer adjust the settings and delete blank line but i want to view in editplus
    Element is getting deleted but the index is not getting deleted
    Please let me know Thanks in advance

    Is this an InDesign question? You are talking about PDFs. Are they exported from InDesign, and you are asking how to fix them some way in InDesign before exporting again to PDF? Or are you placing PDFs into InDesign. If neither of these is your question, you may want to ask over in the Acrobat forum.

  • Problem while populating XML using CSV data

    Hi,
    We are trying to populate a XML file of nested structure from a CSV file. The performance is found to be degrading much.
    While debugging, we found that the issue is because BODS is generating certain nodes in the XML multiple times. This has increased the number of rows that are processed by many fold. This in turn is hitting the performance.
    The structure of our target XSD schema is something like this
    CreateUpdateNode
       |
       |
         Production
            |
            |
               Asset
                 |
                 |
                 Budget
    CreateUpdateNode is the outer root element which is nested with inner elements as shown. Each of these  nodes has their own child elements like
    production name,Asset name,Budget name e.t.c
    The source is a CSV file containing multiple rows. While executing the job, the ideal case should be:
    one CreateUpdateNode block for each input row. But here the nodes are generated multiple times in target XML.
    We tried the below approach:
    Generate a column for row number in the source, and during mapping, put a WHERE clause for each node such as WHERE row number=1.
    Then the nodes are generated as we expect, but in this approach we will get only the data in first row (as row number=1).
    Please suggest a suitable solution
    Thanks ,
    Prateek
    Edited by: Prateek_Naidu on Mar 9, 2012 6:20 AM
    Edited by: Prateek_Naidu on Mar 9, 2012 6:31 AM

    Dear Mr. Prateek
    have you already solved this problem?
    i got same problem with you.
    i have xml schema with alot of nested attribute.
    BODS generating my attribute data  multiple times as much as data row.
    can you give me advice to solved this problem?

Maybe you are looking for

  • InDesign crashes every time I try to open it

    Help please!!!! Every time I try to open Indesign it crashes and I have done the updates and it is still crashing before I can even open a file or do anything!!! Please help!

  • Document could not be saved error

    Whenever I go back to a PDF that I created or downloaded, and add comments or highlights, and then try to save it, I get an error message saying "The document could not be saved.  The file may be read only . . ."  But the file is NOT read-only and th

  • Problems with my new Video iPod

    Hi, I just got a brand new black 30GB video iPod, so far it has been great. However, I've noticed a problem with the HD. Whenever the HD is spinning up and the iPod is moved you can hear the HD clunk. It also tends to make a odd whirring noise when I

  • Exporting to JPEG as a batch

    Hi, I'm working on a project where I'm exporting a large number of InDesign pages to JPEGs. I'll have to repeat the process several times as I make edits (therefore having to replace the old ones). Everytime you replace all the pages you have to say

  • Adding album cover art

    So, I have an album with no cover art (and it's not a common record so iTunes can't find it when using the Get Album Artwork feature), so I have to add it manually. I select all the songs and klick "View info"->"Album artwork" I drag and drop my imag