Whitespace in XML blows up my code

I know this points to bad code. Here's my question. First of all I have to run java 1.3.xx for this project. I've created a web service returning data to the client. The client is using:
javax.xml.parsers.DocumentBuilder;
javax.xml.parsers.DocumentBuilderFactory;
to build the document. Also I had to import
org.w3c.dom
so I assume that's the implementation. As the data is in a proprietary format I used the following to get the nodes and values I wanted:
    for(int a = 0; a < tmp.getChildNodes().getLength(); a++)
      Node type = null;
      Node name = null;
      if(tmp.getChildNodes().item(a).getChildNodes().item(0).getNodeName().equals("FieldName"))
        name = tmp.getChildNodes().item(a).getChildNodes().item(0);
      if(tmp.getChildNodes().item(a).getChildNodes().item(1).getNodeName().equals("FieldName"))
        name = tmp.getChildNodes().item(a).getChildNodes().item(1);etc etc. All was fine until I changed my web service to return a more human readable format a la
<mainNode>
  <childNode>value</childNode>
  <childNode>value</childNode>
</mainNode>  I added the new lines and the indenting. I get null pointers from the Document parsing. So, I guess the whitespace breaks things. Is there a better parser I should be using? Do all parsers have idiosyncracies like this? Should I be doing some type of formatting the data prior to parsing?
Thanks
ST

Dr., I'm glad to see that you're still posting here. I've been away for a while.
I'm curious and confused. Consider the following:
ex 1:
<elementA>
  <elementB>value</elementB>
  <elementB>value</elementB>
</elementA>
ex 2:
<elementA><elementB>value</elementB><elementB>value</elementB></elementA>Aren't both examples syntactically the same? This is the difference that I am seeing. The second example works with my code, the first does not.
Thank you for your thoughts.
ST

Similar Messages

  • Generation of xml file from java code

    hi,
    I want to manipulate data in a xml file with java code.I have read data from xml file and also changed it. But i am unable to covert it again in xml file from java code. Can you please tell me how i can do this?

    Let me know which parser are you using currently for reading xml files so that i assist you. For now, you can refer to STAX Parser API under this link
    http://java.sun.com/webservices/docs/1.6/tutorial/doc/SJSXP3.html

  • How to modify an existing xml file from java code.

    Hi
    I have worked on creating a new xml file from java code using xmlbeans.But if i try to modify an already existing file using java code I am unable to get errorfree xmlfile.
    For example if xml file(studlist.xml) is as below:
    <?xml version="1.0" encoding="UTF-8"?>
    <StudentList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="D:\kchaitanya\xmlprac1\abc\Studlist.xsd">
         <Student>
              <Name>ram</Name>
              <Age>27</Age>
         </Student>
    <Student>
              <Name>sham</Name>
              <Age>26</Age>
         </Student>
    </StudentList>
    Now suppose i have set name to victor using student.setName,
    and set age to 20 using setAge from javacode,
    the new xml file is as follows:
    <?xml version="1.0" encoding="UTF-8"?>
    <StudentList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="D:\kchaitanya\xmlprac1\abc\Studlist.xsd">
         <Student>
              <Name>ram</Name>
              <Age>27</Age>
         </Student>
    <Student>
              <Name>sham</Name>
              <Age>26</Age>
         </Student>
    </StudentList>
    <Student>
              <Name>victor</Name>
              <Age>20</Age>
         </Student>
    As observed this is not a valid xml file.But how can i modify without any errors?

    I know it's an old post, but I found this while doing a google search for something else, and don't like to leave it un-aswered
    Just in case anyone has a similar problem... In this case the new elements have been appended outside of the root element
    What you need to do is first get the root element and then append the new children to that, there are several ways of getting the root element, which depend on what you want to do with the elements you get back here's a simple (incomplete) way.
    // gets the root element of the specified file (code not shown)
    Element rootElement= new SAXReader().read(file).getRootElement();Then just append the new elements as below (this is non-generic code and would need to be modified for your situation)
    // write a new student element
    Element student = document.createElement("Student");  // creates the new student
    rootElement.appendChild(student); // ***appends it to the root element***
    Element name = document.createElement("Name"); // creates the name element
    name.appendChild(document.createTextNode("Fred")); // adds the name text to the name element
    student.appendChild(name); // appends the name to the student
    Element age= document.createElement("Age"); // creates the age element
    age.appendChild(document.createTextNode("26")); // adds the age text to the age element
    student.appendChild(age); // appends the name to the studentThen flush ya buffers or whatever and write the file
    Edited by: Dream-Scourge on Apr 23, 2008 11:10 AM

  • Whitespaces in XML during message mapping not preserved

    I use a twostep mapping process during Interface Mapping. The first one is the standard message mapping and the second one is a Java mapping. However, during the second step, the white spaces that should be preserved from the output of the first mapping is not there anymore. I created the XSD and specified in the details that the white spaces should be preserved.
    I need the whitespaces since the output of the second mapping would be used for file content conversion in a file adapter to create the output:
    MSGTYP CONTROLNOMSGID VALUE1VALUE2 VALUEn.....
    Is there any way to preserve the white spaces?
    Thanks!
    Best Regards,
    Rommel Mendoza

    This is odd. Java won't condense/trim the whitespaces unless explicitely told so.
    Where are you seeing the missing whitespaces?
    Please notice that SXMB_MONI won't show the spaces because it uses a HTML representation of the XML (and, by default, HTML condenses the whitespaces). But the actual XML file should have all the spaces (check the XML document source code, through mouse right click over payload, to be sure).
    Also, what are the conversions you do in the java mapping?
    Are you sure the java mapping input has the whitespaces?
    Regards,
    Henrique.

  • Preserve whitespace in xml parsing

    Hi,
    I am using PL.SQL to parse XML documents using DBMS_XMLDOM..
    and using XMLTYPE...
    Below is the code...
    set serveroutput on
    declare
         var_xmltype     XMLType;
         doc          dbms_xmldom.DOMDocument;
         ndoc          dbms_xmldom.DOMNode;
         docelem          dbms_xmldom.DOMElement;
         node          dbms_xmldom.DOMNode;
         l_loop_group_8_node_list          dbms_xmldom.DOMNodelist;
         l_loop_group_8_node_list_count          number(10);
         l_loop_group_8_sub_node_list          dbms_xmldom.DOMNodelist;
         l_lin_segment_node          dbms_xmldom.DOMNode;
         l_lin_segment_child_node     dbms_xmldom.DOMNode;
         l_loop_group_8_count number(10);
         p_clob_message CLOB;
         l_clob_message CLOB;
         CURSOR c is SELECT * from emx_message_storage where emx_message_id = '170615';
    begin
    for r in c loop
    p_clob_message := r.message_clob;
    end loop;
         var_xmltype := xmltype (p_clob_message);
         -- Create DOMDocument handle
         doc :=     dbms_xmldom.newDOMDocument (var_xmltype);
         ndoc := dbms_xmldom.makeNode (doc);
         docelem := dbms_xmldom.getDocumentElement (doc);
         -- Access Loop-Group_8 Node:
         l_loop_group_8_node_list := dbms_xmldom.getElementsByTagName(docelem, 'Loop-Group_8');
         l_loop_group_8_node_list_count := dbms_xmldom.getlength (l_loop_group_8_node_list);
         --dbms_output.put_line ('Number of Loop-Group_8 Nodes =' || l_loop_group_8_node_list_count);
         FOR l_ka IN 0..(l_loop_group_8_node_list_count-1) LOOP
              -- Get ith Loop-Group_8 node.
              node := dbms_xmldom.item (l_loop_group_8_node_list, l_ka);
              l_loop_group_8_sub_node_list := dbms_xmldom.getChildNodes (node);
              -- Get Segment-LIN
              l_lin_segment_node := dbms_xmldom.item (l_loop_group_8_sub_node_list,0);
              l_lin_segment_child_node := dbms_xmldom.getFirstChild (l_lin_segment_node);
              --dbms_output.put_line ('Before,' || dbms_xmldom.getNodeName (l_lin_segment_child_node) || ' = '  || dbms_xmldom.getNodeValue (DBMS_XMLDOM.getFirstChild(l_lin_segment_child_node)));
              dbms_xmldom.setNodeValue (DBMS_XMLDOM.getFirstChild(l_lin_segment_child_node), l_ka+1);
              --dbms_output.put_line ('After,' || dbms_xmldom.getNodeName (l_lin_segment_child_node) || ' = '  || dbms_xmldom.getNodeValue (DBMS_XMLDOM.getFirstChild(l_lin_segment_child_node)));
         END LOOP;
         DBMS_LOB.CreateTemporary(l_clob_message, TRUE);
         dbms_xmldom.writeToClob (doc, l_clob_message);
         dbms_xmldom.freeDocument(doc);
         update emx_message_storage set message_clob = l_clob_message where emx_message_id = '149329';
    end;
    The code works fine.. except for the fact that when in the input XML message i get one element as
    <Element-3042> </Element-3042>
    it converts it to
    <Element-3042/>
    The whitespace is removed...
    I tried using the xml parser method...and whitespacepreserver optioin...but it creates some extra lines...
    Which i dont want.
    Please suggest.
    Thanks,
    Rosh

    Difficult to read non-formatted code, so pardon not looking at it and trying to spot the problem/error. However, whitespaces seem to work fine for me (tested on 10.2.0.4). Note the resulting XML for a string value, a whitespace value and a null.
    SQL> create table foo_tab( attr1 number, attr2 varchar2(10) );
    Table created.
    SQL>
    SQL> insert into foo_tab values( 1, 'test 123' );
    1 row created.
    SQL> insert into foo_tab values( 2, ' ' );
    1 row created.
    SQL> insert into foo_tab values( 3, null );
    1 row created.
    SQL> commit;
    Commit complete.
    SQL>
    SQL> col XML format a50
    SQL> select
      2          XmlElement( "Row",
      3                  XmlForest(
      4                          attr1 as "Name",
      5                          attr2 as "Value"
      6                  )
      7          )               as XML
      8  from       foo_tab
      9  /
    XML
    <Row><Name>1</Name><Value>test 123</Value></Row>
    <Row><Name>2</Name><Value> </Value></Row>
    <Row><Name>3</Name></Row>
    SQL>

  • Creating an xml file from abap code

    Hello All,
    Please let me know which FM do I need to execute in order to create an XML file from my ABAP code ?
    Thanks in advance,
    Paul.

    This has been discussed before
    XML files from ABAP programs

  • Updating an existing xml file using java code

    hi friends,
    I have simple problem, I have an existing xml file and I want to update some of the values in the file.
    can any one send me the java code for that.
    bye.
    -harish

    org.w3c.dom.Document d = parseXmlFile("D:/www/Detailcache/detail.xml", false);
    public static Document parseXmlFile(String filename, boolean validating) {
    try {
    // Create a builder factory
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(validating);
    // Create the builder and parse the file
    Document doc = factory.newDocumentBuilder().parse(new File(filename));
    return doc;
    } catch (Exception e) {
    System.out.println("ERROR-->");e.printStackTrace();
    return null;
    look at .. for more related examples
    http://javaalmanac.com/egs/javax.xml.parsers/BasicDom.html?l=rel

  • How to delete a perticular node from xml file using java code

    Hii All,
    Now i am trying to delete a perticular node from xml file.Like...
    XML file:
    <Licence>
    <SERVER>
    <was id="1">1</was>
    <was id="2">2</was>
    </SERVER>
    </LICENCE>
    I am working in messaging service using JABBER framework with whiteboard facility.
    Here Some commands i have created to add,modify,delete nodes from xml file.They Are
    1.If u want to add a new node then.
    create Licence.SERVER <ss id="3">ddd</ss> lic.xml
    (here u want to add a new node called "ss" under Licence.SERVER.
    And lic.xml is tyhe xml file name where it was saved.
    2.If u want to delete a node(Suppose <was id="1">),then the command should be
    delete Licence.SERVER.was:id='"1" lic.xml
    A problem arises that here it find two was attributes.And it delete the last was attribute,not the requested node.
    PLEASE HELP ME IN SOLVING THIS CODE..
    ------------------------------------

    Looks like you clicked on "Post" before you pasted in the code you were talking about.

  • How to Read and Generate XML file from java code.

    hi guys,
    how to read the xml file (Condition :we know only DTD or Shema only).
    How to Generate the new xml file ?(using Shema )
    And one more how directly Generate the xml from DB?
    Pleas with code or any URL

    Using XMLbeans you can generate Java objects from an XSD schema (perhaps DTDs aswell)
    Then you can create an instance of the Document object and ask it to write itself.
    This will create an XML document complient to the schema.
    XMLBeans generates a "type" safe DOM where you can only ever have a structure compilent to you schema.
    matfud

  • Reference faces-config.xml file from java code.

    I would like to reference the navigation rules I have set up in my faces-config.xml file from inside my source code.
    For example:
    Navigation Rule:
    <navigation-rule>
    <from-view-id>*</from-view-id>
    <navigation-case>
    <from-outcome>pricingEngine</from-outcome>
    <to-view-id>/faces/template/t_pricing_engine.jsf</to-view-id>
    <redirect/>
    </navigation-case>
    </navigation-rule>
    I would like do some sort of lookup by 'pricingEngine' and get '/faces/template/t_pricing_engine.jsf' back.
    Any ideas?

    I would like to reference the navigation rules I have set up in my faces-config.xml file from inside my source code.
    For example:
    Navigation Rule:
    <navigation-rule>
    <from-view-id>*</from-view-id>
    <navigation-case>
    <from-outcome>pricingEngine</from-outcome>
    <to-view-id>/faces/template/t_pricing_engine.jsf</to-view-id>
    <redirect/>
    </navigation-case>
    </navigation-rule>
    I would like do some sort of lookup by 'pricingEngine' and get '/faces/template/t_pricing_engine.jsf' back.
    Any ideas?

  • How to Generate XML File from Java Code.

    I want to generate the xml file from the java code.
    Could you plz suggest any webSite address with example?

    Here is the code
    import java.io.File;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.FactoryConfigurationError;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerConfigurationException;
    import javax.xml.transform.TransformerException;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    public class CreateXML {
         private DocumentBuilderFactory factory = null;
         private DocumentBuilder builder = null;
         private Document document = null;
         public CreateXML() {
              try {
                   factory = DocumentBuilderFactory.newInstance();
                   builder = factory.newDocumentBuilder();
                   document = builder.newDocument();
              } catch (FactoryConfigurationError e) {
                   e.printStackTrace();
              } catch (ParserConfigurationException e) {
                   e.printStackTrace();
         /** Creates the document for xml. */
         public Document createDocument(){
              try{               
                   Element root = document.createElement("Root");
                   Element child = document.createElement("child");
                   root.appendChild(child);
                   document.appendChild(root);
              }catch(RuntimeException e){
                   e.printStackTrace();
              return document;
         /** Saves the document as xml. */
         public void saveDocument(Document document){
              try{
                   TransformerFactory transFactory = TransformerFactory.newInstance();
                   Transformer transformer = transFactory.newTransformer();
                   DOMSource source = new DOMSource(document);
                   StreamResult stream = new StreamResult(new File("sample.xml"));
                   transformer.transform(source, stream);
                   System.out.println("XML Created !!");
              }catch(TransformerConfigurationException e){
                   e.printStackTrace();
              } catch (TransformerException e) {
                   e.printStackTrace();
         public static void main(String args[]){
              CreateXML createXML = new CreateXML();
              Document document = createXML.createDocument();
              createXML.saveDocument(document);
    }

  • How to prohibit leading and traling whitespace in XML Schema

    I want to prohibit the use of leading and trailing whitespace in an element but besides that all other content is allowed.
    For examble <   word? > should give a validation error.
    I do not want to use
    <whiteSpace value="collapse"/>
    Because it doesn't give a validation error.
    Is it possible to make a pattern og in some other way solve my problem?
    Thanks in advance, Martin

    Here is an example schema snippet (not a complete schema!) that does what you want I think, using a regular expresssion pattern, allowing one or more non-white-space characters followed by an optional sequence of any character followed by one or more non-white-space characters:
    Code Snippet
            <xs:element name="foo" maxOccurs="unbounded">
              <xs:simpleType>
                <xs:restriction base="xs:string">
                  <xs:pattern value="\S+(.*\S+)*"/>
                </xs:restriction>
              </xs:simpleType>
            </xs:element>
    Here are some example elements with valid contents:
    Code Snippet
      <foo>a</foo>
      <foo>a b</foo>
      <foo>a b c d e f g</foo>
    And here some elements with invalid contents that validation would catch:
    Code Snippet
      <foo> a</foo>
      <foo>a </foo>

  • Split XML in Multiple XML files with Java Code

    Hi guys , i have following xml file as input ....
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <T0020
    xsi:schemaLocation="http://www.safersys.org/namespaces/T0020V1 T0020V1.xsd"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.safersys.org/namespaces/T0020V1">
    <INTERFACE>
    <NAME>SAFER</NAME>
    <VERSION>04.02</VERSION>
    </INTERFACE>
    <TRANSACTION>
    <VERSION>01.00</VERSION>
    <OPERATION>REPLACE</OPERATION>
    <DATE_TIME>2009-09-01T00:00:00</DATE_TIME>
    <TZ>CT</TZ>
    </TRANSACTION>
    <IRP_ACCOUNT>
    <IRP_CARRIER_ID_NUMBER>274845</IRP_CARRIER_ID_NUMBER>
    <IRP_BASE_COUNTRY>US</IRP_BASE_COUNTRY>
    <IRP_BASE_STATE>AR</IRP_BASE_STATE>
    <IRP_ACCOUNT_NUMBER>55002</IRP_ACCOUNT_NUMBER>
    <IRP_ACCOUNT_TYPE>I</IRP_ACCOUNT_TYPE>
    <IRP_STATUS_CODE>100</IRP_STATUS_CODE>
    <IRP_STATUS_DATE>2007-11-06</IRP_STATUS_DATE>
    <IRP_UPDATE_DATE>2009-08-03</IRP_UPDATE_DATE>
    <IRP_NAME>
    <NAME_TYPE>LG</NAME_TYPE>
    <NAME>A P SUPPLY CO</NAME>
    <IRP_ADDRESS>
    <ADDRESS_TYPE>PH</ADDRESS_TYPE>
    <STREET_LINE_1>1400 N OATS</STREET_LINE_1>
    <STREET_LINE_2/>
    <CITY>TEXARKANA</CITY>
    <STATE>AR</STATE>
    <ZIP_CODE>71854</ZIP_CODE>
    <COUNTY>MILLER</COUNTY>
    <COLONIA/>
    <COUNTRY>US</COUNTRY>
    </IRP_ADDRESS>
    <IRP_ADDRESS>
    <ADDRESS_TYPE>MA</ADDRESS_TYPE>
    <STREET_LINE_1>P O BOX 1927</STREET_LINE_1>
    <STREET_LINE_2/>
    <CITY>TEXARKANA</CITY>
    <STATE>AR</STATE>
    <ZIP_CODE>75504</ZIP_CODE>
    <COUNTY/>
    <COLONIA/>
    <COUNTRY>US</COUNTRY>
    </IRP_ADDRESS>
    </IRP_NAME>
    </IRP_ACCOUNT>
    <IRP_ACCOUNT> ..... </IRP_ACCOUNT>
    <IRP_ACCOUNT> ..... </IRP_ACCOUNT>
    <IRP_ACCOUNT> ..... </IRP_ACCOUNT>
    </T0020>
    and i want to take this xml file and split it into multiple files through java code like this ...
    File1.xml
    <T0020>
    <IRP_ACCOUNT> ..... </IRP_ACCOUNT>
    <IRP_ACCOUNT> ..... </IRP_ACCOUNT>
    </T0020>
    File2.xml
    <T0020>
    <IRP_ACCOUNT> ..... </IRP_ACCOUNT>
    <IRP_ACCOUNT> ..... </IRP_ACCOUNT>
    </T0020>
    like wise...
    Each xml file contain maximum 10 or 15 IRP_ACCOUNT.
    Can somebody please help me ? How can i do it with stax like start element and all ?
    thanks in advance.

    Ah, sorry, strike that. You want multiple files. I think the easiest way is to simply parse with DOM. [http://www.w3schools.com/xpath/default.asp] . And here [http://www.w3schools.com/xpath/default.asp].
    You can output the various XML elements using a PrintWriter or creating a separate DOM document for each file you want to create and serializing that.
    - Saish

  • Preserve paragraph whitespace in XML Data

    I'm having problems using the Spry Gallery. I've added a new
    tag called <artistbio>, which contains paragraphs. How do I
    get line breaks or whitespace to be preserved. Using HTML tags
    doesn't appear to work.
    I'm sure it's something simple, but this is my first venture
    into XML.
    example:
    http://www.gracepointe.net/gallery/
    an xml file with whitespace:
    http://www.gracepointe.net/gallery/r_baldwin.xml
    thanks!
    clint

    Marco,
    Thanks for your reply.
    Well, I am not building a SOAP Envelope for posting the data to the service.
    I am using a plain XML here, so I used REPLACE(<XML Data>,' ','%20') which solved my issue.
    If you think my solution might have some side effects then please suggest me.
    Thanks,
    Raj.

  • Preserving whitespace in XML fields?

    I have a requirement to preserve the character positioning within an XML field. I am using the standard XML/HTTP port for output from the ALE interface. One of the fields contains multiple spaces within the data. It appears the default setting of the XML processor is to condense these spaces into a single space. The xsl:preserve-space pre-processor command should preserve the whitespace, Does anyone know how to configure the SAP XML processor to do this?   Thanks!
    We are using basis 6.20

    There's a setting in Flash's XML object called ignoreWhitespace that you need to set to false (by default its true).
    Something like this should work:
    function convertStringToXML(source:String):XML
         var originalSettings:Object = XML.settings();
         try
              XML.ignoreWhitespace = false;
              var xmlTree:XML = new XML(source);
         finally
              XML.setSettings(originalSettings);
         return xmlTree;
    - robin

Maybe you are looking for

  • How do i format an external hard drive for use on both windows and mac book air?

    how do i format an external hard drive for use on both windows pc and mac book air?

  • Highlighting current day in month view.....

    Is there an option to highlight the current day? Maybe shade it a different color? If I look at the mini calendar in the left pane the current day is highlighted blue but on the calendar itself the box for the day is white like every other day. Thank

  • Why doesn't my Links panel work?

    Pix, etc not listed in links panel. I know there's a quick answer to this question but our corporate idiots who built this forum didn't bother making it possible for anyone to actually search the forum directly, a feature that has been available on e

  • Importing movies to iPod gives an error

    I'd like to import a movie from a bought Music-CD to the iPod. The movie is available as *.mov and *.mpg. importing them into iTunes worked but converting it for the use in iPod gives the message "An unknown error appeared (-50)" What's wrong with iT

  • Convert number to varchar datatype

    hi, I am working in oracle 9i. i am using two variables v_trigger_time varchar2(1000); v_min_run_date varchar2(1000); v_int_count NUMBER; datatype as VARCHAR2 and Number .ie ) HH:MI here is the query : select to_char(min(RUN_START_TIME),'HH24:MI') in