Unmarshalling a DOM node to an XML file with JAXB

I'm trying to unmarshall a DOM node to an XML file using JAXB. However I keep receiving a NullPointerException. This only seems to occur when I create the DOM Node from scratch. The stack trace looks like the following:
java.lang.NullPointerException
        at com.sun.xml.bind.unmarshaller.SAXUnmarshallerHandlerImpl.startElement
(SAXUnmarshallerHandlerImpl.java:87)
        at com.sun.xml.bind.unmarshaller.DOMScanner.visit(DOMScanner.java:109)
        at com.sun.xml.bind.unmarshaller.DOMScanner.parse(DOMScanner.java:64)
        at com.sun.xml.bind.unmarshaller.UnmarshallerImpl.unmarshal(Unmarshaller
Impl.java:149)
        at Main.main(Main.java:103)(If I unmarshal an XML file into a DOM node, I can successfully marshall the DOM node out to a new XML file using JAXB without error.)
Any insight into what I am doing wrong would be greatly appreciated!
Sample code and XSD follow...
Sample Code:
import itemlistsample.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
public class Main
  public static void main(String[] args)
      try
          JAXBContext jc = JAXBContext.newInstance( "itemlistsample" );
          Unmarshaller u = jc.createUnmarshaller();
          * Set up DOM Node Document Object.
          DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
          dbf.setNamespaceAware(true);                   
          DocumentBuilder db = dbf.newDocumentBuilder(); 
          Document doc = db.newDocument();
          System.out.println();
          System.out.println();
          System.out.println("Create a DOM Node and unmarshall to an XML file");
          * Generate elements within DOM document
          Element itemListElt = (Element)doc.createElement("item_list");
          Element itemInfo = (Element)doc.createElement("item_info");
          Element name = (Element)doc.createElement("name");
          Element price = (Element)doc.createElement("price");
          * 3-Ring Binder @ 4.99
          name.appendChild(doc.createTextNode("3-Ring Binder"));
          itemInfo.appendChild(name);
          price.appendChild(doc.createTextNode("4.99"));
          itemInfo.appendChild(price);
          itemListElt.appendChild(itemInfo);
          * Large Paper Clips @ 1.23
          itemInfo = (Element)doc.createElement("item_info");
          name = (Element)doc.createElement("name");
          price = (Element)doc.createElement("price");
          name.appendChild(doc.createTextNode("Large Paper Clips"));
          itemInfo.appendChild(name);
          price.appendChild(doc.createTextNode("1.23"));
          itemInfo.appendChild(price);
          itemListElt.appendChild(itemInfo);
          doc.appendChild(itemListElt);
          * Display DOM document as a sanity check
          itemListElt = doc.getDocumentElement();
          System.out.println(itemListElt.getTagName());
          NodeList nl = itemListElt.getElementsByTagName("item_info");
          traverse("  ", nl.item(0));
          * Use JAXB to unmarshal the DOM document into
          * an instance of the generated JAXB class for
          * the root element.  Stack trace occurs here!
          ItemListType il = (ItemListType)u.unmarshal(doc);
          * Marshal to an XML file
          Marshaller m = jc.createMarshaller();
          m.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE );
          m.marshal( il, new FileOutputStream("item_new.xml") );
      catch (Exception e)
     e.printStackTrace();
  public static void traverse(String indent, Node n)
    if (n != null)
      if (n.getNodeName() != null)
        System.out.println(indent + n.getNodeName());
        traverse(indent + "  ", n.getFirstChild());
      if (n.getNodeValue() != null)
        System.out.println(indent + n.getNodeValue());
      traverse(indent, n.getNextSibling());
}Sample XSD:
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
     <xsd:element name="item_list" type="ItemListType"/>
     <xsd:complexType name="ItemListType">
          <xsd:sequence>
               <xsd:element name="item_info" type="ItemInfoType" maxOccurs="unbounded"/>
          </xsd:sequence>
     </xsd:complexType>
     <xsd:complexType name="ItemInfoType">
          <xsd:sequence>
               <xsd:element name="name" type="xsd:string"/>
               <xsd:element name="price" type="xsd:double"/>
          </xsd:sequence>
     </xsd:complexType>
</xsd:schema>

Modified schema
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="item_list">     
<xsd:complexType>          
<xsd:sequence>               
<xsd:element ref="item_info" maxOccurs="unbounded"/>     
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="item_info">
     <xsd:complexType>          
<xsd:sequence>               
<xsd:element name="name" type="xsd:string"/>     
     <xsd:element name="price" type="xsd:double"/>     
     </xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>

Similar Messages

  • Unmarshaling XML file with JAXB from JAR doesn't work?

    Hi
    I'm pretty new to JAXB... I'm unmarshaling an XML file, and everything works fine in my JUnit test, using XML files. However, the caller of my unmarshalling is a Web Start application using signed JARs.
    When I try to access the XML file, I log the URL and get an exception:
    INFO[slf5s.PRIORITY] javawsApplicationMain[slf5s.THREAD] ch.ige.main.client.menu.MenuBuilder[slf5s.CATEGORY] Creating menu from URL jar:file:C:/Program%20Files/JRE/1.4.2/cache/http/...Main.jar!/res/JippsAdminMenuBaum.xml[slf5s.MESSAGE]
    ERROR[slf5s.PRIORITY] javawsApplicationMain[slf5s.THREAD] ch.ige.main.client.MenuPane[slf5s.CATEGORY] exception caught[slf5s.MESSAGE]
    java.io.IOException: Couldn't unmarshal configuration from java.util.jar.JarVerifier$VerifierStream@15f1f9c: null
         at ch.ige.main.client.menu.MenuBuilder.unmarshalConfiguration(MenuBuilder.java:110)
         at ch.ige.main.client.menu.MenuBuilder.<init>(MenuBuilder.java:86)
         at ch.ige.main.client.MenuPane.createMenuBuilder(MenuPane.java:485)
         at ch.ige.main.client.MenuPane.createTreeLevel(MenuPane.java:460)
         at ch.ige.main.client.MenuPane.jbInit(MenuPane.java:316)
         at ch.ige.main.client.MenuPane.<init>(MenuPane.java:122)
         at ch.ige.jippsadmin.MepJipps.<init>(MepJipps.java:32)
         at ch.ige.jippsadmin.JippsMain.run(JippsMain.java:64)
         at ch.ige.auth.ClientAuthenticator.executePrivilegedCode(ClientAuthenticator.java:166)
         at ch.ige.authz.client.AuthMain.executePrivilegedCode(AuthMain.java:128)
         at ch.ige.authz.client.AuthMain.run(AuthMain.java:213)
         at ch.ige.jippsadmin.JippsMain.main(JippsMain.java:77)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
         at java.lang.reflect.Method.invoke(Unknown Source)
         at com.sun.javaws.Launcher.executeApplication(Unknown Source)
         at com.sun.javaws.Launcher.executeMainClass(Unknown Source)
         at com.sun.javaws.Launcher.continueLaunch(Unknown Source)
         at com.sun.javaws.Launcher.handleApplicationDesc(Unknown Source)
         at com.sun.javaws.Launcher.handleLaunchFile(Unknown Source)
         at com.sun.javaws.Launcher.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)Btw, does anyone know where to find the runtime JARs that are required for JAXB (from JWSDP 1.5)?
    Thanks & best regards,
    Eric

    Well... once again this was a ClassLoader problem... solved!

  • Converting Dom Document object into XML file removes the DTD

    Hi All
    My xml is dtd. I have one xml file. i changed the node value after that i want to create a xml file with the same name. I created new xml file but i am not seeing the old dtd in the new file. This process is done with the help of jaxp.
    My code is given below
    File fileInput = new File("input.xml");
              File fileOutput = new File("output.xml");
              DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
              factory.setExpandEntityReferences(false);
              DocumentBuilder builder = factory.newDocumentBuilder();
              Document document = builder.parse(fileInput);
              TransformerFactory tFactory = TransformerFactory.newInstance();
              Transformer transformer = tFactory.newTransformer();
    transformer.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "true");
              transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
              DOMSource source = new DOMSource(document);
              FileOutputStream fos = new FileOutputStream(fileOutput);
              StreamResult result = new StreamResult(fos);
              transformer.transform(source, result);
    Thanks in advance

    The Transformer API does not guarantee the preservation of that information. You may want to check the DOM L3 Load/Save package (http://java.sun.com/javase/6/docs/api/index.html). Alternatively, you may force things by setting the additional output properties 'doctype-public' and 'doctype-system'.

  • Why we need to conver Context  Node data into XML file----Export to Excel

    Hi All,
    Let me clarify my dought........today i have gone through the concept of  "Exporting Context Data Using the Webdynpro Binary cache" in SAP Online Help.
    From the SAP Online Help pdf document, i have found that, the context node data has been converted first in to XML file,after that file had been stored in the web dynpor binary cache...bla....bla.........
    Here my qtn is why they had converted context node data into XML file. With out doing that can not we export context node data to excel file..?
    Regards
    Seshu
    Edited by: Sesshanna D on Dec 19, 2007 7:25 AM

    Hi Sesshanna,
    it is not neccessary to do that but xml has the advantage, that it can be easily transformed into every output format that might occur in later project stages.
    If it's simply about blowing out some Excel, I suggest using an OSS library such as jexcelAPI or Jakarta POI and building the Excel how you need it.
    regards,
    Christian

  • Comparing nodes in two xml files

    I need help with a flex app i am making. My skill level in flex is pretty much basic, so some of the questions may seem easy but they r not to me
    I need an application that will load two external xml files and compare nodes. The xml files are pretty much identical except for the values ofcourse. After that i need to write this data to a new xml file which my flex app will generate. Can anyone plz give me an example code which i can later modify for my own application. You can give me any type of an example with the simplest xml files.
    Thank you in advance

    "for in" and "for each in" statements can be used to iterate through the nodes. If the two xml files are of same structure , you can easily compare the node attributes. Here is the link to the livedocs page for looping through xml nodes
    http://livedocs.adobe.com/flex/3/html/help.html?content=13_Working_with_XML_08.html
    Create xml from string
    http://www.cflex.net/showFileDetails.cfm?ChannelID=1&ObjectID=784
    Message was edited by: Subeesh Arakkan

  • Problems with reading XML files with ISO-8859-1 encoding

    Hi!
    I try to read a RSS file. The script below works with XML files with UTF-8 encoding but not ISO-8859-1. How to fix so it work with booth?
    Here's the code:
    import java.io.File;
    import javax.xml.parsers.*;
    import org.w3c.dom.*;
    import java.net.*;
    * @author gustav
    public class RSSDocument {
        /** Creates a new instance of RSSDocument */
        public RSSDocument(String inurl) {
            String url = new String(inurl);
            try{
                DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                Document doc = builder.parse(url);
                NodeList nodes = doc.getElementsByTagName("item");
                for (int i = 0; i < nodes.getLength(); i++) {
                    Element element = (Element) nodes.item(i);
                    NodeList title = element.getElementsByTagName("title");
                    Element line = (Element) title.item(0);
                    System.out.println("Title: " + getCharacterDataFromElement(line));
                    NodeList des = element.getElementsByTagName("description");
                    line = (Element) des.item(0);
                    System.out.println("Des: " + getCharacterDataFromElement(line));
            } catch (Exception e) {
                e.printStackTrace();
        public String getCharacterDataFromElement(Element e) {
            Node child = e.getFirstChild();
            if (child instanceof CharacterData) {
                CharacterData cd = (CharacterData) child;
                return cd.getData();
            return "?";
    }And here's the error message:
    org.xml.sax.SAXParseException: Teckenkonverteringsfel: "Malformed UTF-8 char -- is an XML encoding declaration missing?" (radnumret kan vara f�r l�gt).
        at org.apache.crimson.parser.InputEntity.fatal(InputEntity.java:1100)
        at org.apache.crimson.parser.InputEntity.fillbuf(InputEntity.java:1072)
        at org.apache.crimson.parser.InputEntity.isXmlDeclOrTextDeclPrefix(InputEntity.java:914)
        at org.apache.crimson.parser.Parser2.maybeXmlDecl(Parser2.java:1183)
        at org.apache.crimson.parser.Parser2.parseInternal(Parser2.java:653)
        at org.apache.crimson.parser.Parser2.parse(Parser2.java:337)
        at org.apache.crimson.parser.XMLReaderImpl.parse(XMLReaderImpl.java:448)
        at org.apache.crimson.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:185)
        at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:124)
        at getrss.RSSDocument.<init>(RSSDocument.java:25)
        at getrss.Main.main(Main.java:25)

    I read files from the web, but there is a XML tag
    with the encoding attribute in the RSS file.If you are quite sure that you have an encoding attribute set to ISO-8859-1 then I expect that your RSS file has non-ISO-8859-1 character though I thought all bytes -128 to 127 were valid ISO-8859-1 characters!
    Many years ago I had a problem with an XML file with invalid characters. I wrote a simple filter (using FilterInputStream) that made sure that all the byes it processed were ASCII. My problem turned out to be characters with value zero which the Microsoft XML parser failed to process. It put the parser in an infinite loop!
    In the filter, as each byte is read you could write out the Hex value. That way you should be able to find the offending character(s).

  • How must getElementsByTagName work on an xml file with namespaces?

    Hello together,
    is there any normative document, which specifies
    which nodes must be returned by
    the org.w3c.dom.Document method
    getElementsByTagName when which was
    created by a namespace aware dom parser
    from an xml file containing namespaces?
    In other words:
    when you have an xml file:
    <someprefix:somenode xmlns:someprefix="http://someuri">
    <someprefix:innertag>
    <someprefix:mostinnertag>
    </someprefix:mostinnertag>
    <someprefix:mostinnertag>
    </someprefix:mostinnertag>
    </someprefix:innertag>
    </someprefix>
    and you call
    document.getElementsByTagName( ... );
    1) How many nodes must be returned when giving
    "mostinnertag" as parameter?
    2) How many nodes when giving "someprefix:mostinnertag" as parameter?
    Is it allowed to use the "non namespaceaware"
    method and not "getElementsByTagNameNS"?
    I know:
    a) xerces returns 2 nodes when using
    alternative 2 and none with alternative 1
    b) oracle xml parser returns 2 nodes when using
    alternative 1 and none when using alternative 2
    Which implementation is right?
    Yours
    Stefan

    I've got some problems with this methos and xerces too.
    Perhaps the two implementations (xerces and oracle) are different. I mean xerces implementation gives you nodes of this name but without namespace and oracles's implementation gives you modes with namespace whose unprefix-name is "mostinnertag".

  • How can I save a XML file with JAXP1.1?

    Dear All.
    I write a program to create XML file with DOM model, but I can't know how to save it? My environment is JAXP1.1 and JDK1.3.1,I has been required not use other XML parser toolkits,only JAXP1.1.
    How can I do? thank you.
    Many person give me a idea the com.sun.xml.tree.XmlDocument, but I can't find the class in API document or JAXP1.1's packages. why?
    what is it? How can i use it?
    thank you very much.

    The way to save an XML Document is using a Transformer.
    To have access to a transformer use the packages :
    import javax.xml.transform.*;
    import javax.xml.transform.dom.*;
    import javax.xml.transform.stream.*;
    Then for saving your Document Object (named dXml) get a Transformer Object with the TransformerFactory Object :
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer();
    Now you have got your Transformer Object, to save your Document Object use the method :
    Document dXml = getMyDocument(); // this is your Document Object.
    OutputStream osSave = getMySaveStream(); // this the OutputStream you need to save your Document.
    try
    t.transform(new DomSource(dXml), new StreamResult(new OutputStreamWriter(osSave)));
    finally
    osSave.close();
    And your Document was now saved.

  • Create xml file with values from context

    Hi experts!
    I am trying to implement a WD application that will have some input fields, the value of those input fields will be used to create an xml file with a certain format and then sent to a certain application.
    Apart from this i want to read an xml file back from the application and then fill some other context nodes with values from the xml file.
    Is there any standard used code to do this??
    If not how can i do this???
    Thanx in advance!!!
    P.S. Points will be rewarded to all usefull answers.
    Edited by: Armin Reichert on Jun 30, 2008 6:12 PM
    Please stop this P.S. nonsense!

    Hi,
    you need to create three util class for that:-
    XMLHandler
    XMLParser
    XMLBuilder
    for example in my XML two tag item will be there e.g. Title and Organizer,and from ur WebDynpro view you need to pass value for the XML tag.
    And u need to call buildXML()function of builder class to generate XML, in that i have passed bean object to get the values of tags. you need to set the value in bean from the view ui context.
    Code for XMLBuilder:-
    Created on Apr 4, 2006
    Author-Anish
    This class is to created for having function for to build XML
    and to get EncodedXML
      and to get formated date
    package com.idb.events.util;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import com.idb.events.Event;
    public class XMLBuilder {
    This attribute represents the XML version
         private static final double VERSION_NUMBER = 1.0;
    This attribute represents the encoding
         private static final String ENCODING_TYPE = "UTF-16";
         /*Begin of Function to buildXML
    return: String
    input: Event
         public String buildXML(Event event) {
              StringBuffer xmlBuilder = new StringBuffer("<?xml version=\"");
              xmlBuilder.append(VERSION_NUMBER);
              xmlBuilder.append("\" encoding=\"");
              xmlBuilder.append(ENCODING_TYPE);
              xmlBuilder.append("\" ?>");
              xmlBuilder.append("<event>");
              xmlBuilder.append(getEncodedXML(event.getTitle(), "title"));
              xmlBuilder.append(getEncodedXML(event.getOrganizer(), "organizer"));
              xmlBuilder.append("</event>");
              return xmlBuilder.toString();
         /End of Function to buildXML/
         /*Begin of Function to get EncodedXML
    return: String
    input: String,String
         public String getEncodedXML(String xmlString, String tag) {
              StringBuffer begin = new StringBuffer("");
              if ((tag != null) || (!tag.equalsIgnoreCase("null"))) {
                   begin.append("<").append(tag).append(">");
                   begin.append("<![CDATA[");
                   begin.append(xmlString).append("]]>").append("</").append(
                        tag).append(
                        ">");
              return begin.toString();
         /End of Function to get EncodedXML/
         /*Begin of Function to get formated date
    return: String
    input: Date
         private final String formatDate(Date inputDateStr) {
              String date;
              try {
                   SimpleDateFormat simpleDateFormat =
                        new SimpleDateFormat("yyyy-MM-dd");
                   date = simpleDateFormat.format(inputDateStr);
              } catch (Exception e) {
                   return "";
              return date;
         /End of Function to get formated date/
    Code for XMLParser:-
    Created on Apr 12, 2006
    Author-Anish
    This is a parser class
    package com.idb.events.util;
    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    import org.xml.sax.XMLReader;
    import com.idb.events.Event;
    import com.sap.tc.webdynpro.progmodel.api.IWDMessageManager;
    public class XMLParser {
    Enables namespace functionality in parser
         private final boolean isNameSpaceAware = true;
    Enables validation in parser
         private final boolean isValidating = true;
    The SAX parser used to parse the xml
         private SAXParser parser;
    The XML reader used by the SAX parser
         private XMLReader reader;
    This method creates the parser to parse the user details xml.
         private void createParser()
              throws SAXException, ParserConfigurationException {
              // Create a JAXP SAXParserFactory and configure it
              SAXParserFactory saxFactory = SAXParserFactory.newInstance();
              saxFactory.setNamespaceAware(isNameSpaceAware);
              saxFactory.setValidating(isValidating);
              // Create a JAXP SAXParser
              parser = saxFactory.newSAXParser();
              // Get the encapsulated SAX XMLReader
              reader = parser.getXMLReader();
              // Set the ErrorHandler
    This method is used to collect the user details.
         public Event getEvent(
              String newsXML,
              XMLHandler xmlHandler,
              IWDMessageManager mgr)
              throws SAXException, ParserConfigurationException, IOException {
              //create the parser, if not already done
              if (parser == null) {
                   this.createParser();
              //set the parser handler to extract the
              reader.setErrorHandler(xmlHandler);
              reader.setContentHandler(xmlHandler);
              InputSource source =
                   new InputSource(new ByteArrayInputStream(newsXML.getBytes()));
              reader.parse(source);
              //return the results of the parse           
              return xmlHandler.getEvent(mgr);
    Code for XMLHandler:-
    Created on Apr 12, 2006
    Author-Anish
    This is a parser class
    package com.idb.events.util;
    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    import org.xml.sax.XMLReader;
    import com.idb.events.Event;
    Created on Apr 12, 2006
    Author-Anish
    *This handler class is created to have constant value for variables and function for get events,
        character values for bean variable,
        parsing thr date ......etc
    package com.idb.events.util;
    import java.sql.Timestamp;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Locale;
    import org.xml.sax.Attributes;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    import org.xml.sax.helpers.DefaultHandler;
    import java.util.*;
    import com.idb.events.Event;
    import com.sap.tc.webdynpro.progmodel.api.IWDMessageManager;
    public class XMLHandler extends DefaultHandler {
         private static final String TITLE = "title";
         private static final String ORGANIZER = "organizer";
         IWDMessageManager manager;
         private Event events;
         private String tagName;
         public void setManager(IWDMessageManager mgr) {
              manager = mgr;
    This function is created to get events
         public Event getEvent(IWDMessageManager mgr) {
              manager = mgr;
              return this.events;
    This function is created to get character for setting values through event's bean setter method
         public void characters(char[] charArray, int startVal, int length)
              throws SAXException {
              String tagValue = new String(charArray, startVal, length);
              if (TITLE.equals(this.tagName)) {
                   this.events.setTitle(tagValue);
              if (ORGANIZER.equals(this.tagName)) {
                   String orgName = tagValue;
                   try {
                        orgName = getOrgName(orgName);
                   } catch (Exception ex) {
                   this.events.setOrganizer(orgName);
    This function is created to parse boolean.
         private final boolean parseBoolean(String inputBooleanStr) {
              boolean b;
              if (inputBooleanStr.equals("true")) {
                   b = true;
              } else {
                   b = false;
              return b;
    This function is used to call the super constructor.
         public void endElement(String uri, String localName, String qName)
              throws SAXException {
              super.endElement(uri, localName, qName);
         /* (non-Javadoc)
    @see org.xml.sax.ErrorHandler#fatalError(org.xml.sax.SAXParseException)
    This function is used to call the super constructor.
         public void fatalError(SAXParseException e) throws SAXException {
              super.fatalError(e);
    This function is created to set the elements base on the tag name.
         public void startElement(
              String uri,
              String localName,
              String qName,
              Attributes attributes)
              throws SAXException {
              this.tagName = localName;
              if (ROOT.equals(tagName)) {
                   this.events = new Event();
         public static void main(String a[]) {
              String cntry = "Nigeria";
              XMLHandler xml = new XMLHandler();
              ArrayList engList = new ArrayList();
              engList = xml.getCountries();
              ArrayList arList = xml.getArabicCountries();
              int engIndex = engList.indexOf(cntry);
              System.out.println("engIndex  :: " + engIndex);
              String arCntryName = (String) arList.get(engIndex);
              System.out.println(
                   ">>>>>>>>>>>>>>>>>>>>" + xml.getArabicCountryName(cntry));
    Hope that may help you.
    If need any help , you are most welcome.
    Regards,
    Deepak

  • Transfer 100M XML file with XSL

    Hi,
    I am trying to transfer 100M XML file with XSL. Input.xml is the XML file, format.xsl is the XSL file. I type in the command line as:
    java org.apache.xalan.xslt.Process -IN input.xml -XSL format.xsl -OUT output.xml
    It got "out of memeory" error. My questions are:
    1. Is it possible to transfer such large XML file with XSLT?
    2. The XSL processor used SAX or DOM to parse XML file?
    3. Any suggestions?
    Thanks.
    James

    maybe?
    java -Xmx200m org.apache.xalan.xslt.Process -IN input.xml -XSL format.xsl -OUT output.xml
    http://java.sun.com/j2se/1.3/docs/tooldocs/win32/java-classic.html

  • Loading XML file with missing elements dynamically through ODI

    Hi Guys ,
    I have the below xml file with two nodes Employee and Address. On a daily basis , sometimes the address element might not come in from the source xml file , but my interface has columns mapped to address elements, and hence it can fail due to the source element not being found in the file or data might not get loaded due to the 'and' condition in the sql query generated between the employee and address elements.  Is there a way where i can load the data dynamically where i can search in the file only for the elements (Employee) present and load data only for those elements dynamically?
    XML File:
    <?xml version="1.0" encoding="UTF-8" ?>
    <EMP>
    <Empsch>
    <Employee>
    <EmployeeID>12345</EmployeeID>
    <Initials>t</Initials>
    <LastName>john</LastName>
    <FirstName>doe</FirstName>
    </Employee>
    <Address>
    <WorkPhone>12345</WorkPhone>
    <WorkAddress>Test 234</WorkAddress>
    </Address>
    </Empsch>
    </EMP>
    Thanks ,
    Revanth Tambisetty

    I was able to resolve it by using left outer joins and referring the table structure from the XSD

  • File Adapter : read XML file with data validation and file rejection ?

    Hello,
    In order to read a XML file with the file adapter, I have defined a XSD that I have imported to my project.
    Now the File Adapter reads the file correctly but it does not give an error when:
    - the data types are not valid. Ex: dateTime is expected in a node and a string is provided
    - the XML file has invalid attributes.
    How can I manage error handling for XML files ?
    Should I write my own Java XPath function to validate the file after is processed ? (here is an example for doing this : http://www.experts-exchange.com/Web/Web_Languages/XML/Q_21058568.html)
    Thanks.

    one option is to specify validateXML on the partnerlink (that describes the file adapter endpoint) such as shown here
    <partnerLinkBinding name="StarLoanService">
    <property name="wsdlLocation"> http://<hostname>:9700/orabpel/default/StarLoan/StarLoan?wsdl</property>
    <property name="validateXML">true</property>
    </partnerLinkBinding>
    hth clemens

  • One to many xml files with file adaptor

    Hi,
    I have a scenario HCM-ABAPProxy--XI-File for one structure I need to generate multiple xml files with 100 records per file.
    this is my input  messag
    MT_in
      Node
         PositionIDs
            descrption
            job
            IsActive
    what I was doing on the ABAP side for every node I have 100 PositionID's sub nodes. so each node should be a sperate file.
    my output structure is
    PositionIDs
        PositionID
          pid
          description
          job
    so there should be one PositionIDs per file which contains 100 PositionID.
    I've multi message mapping without BPM that did not work out just wondering if any one came across the same scenario.
    thanks,
    Joe

    You can not create multiple files without BPM. You can pretty much perform multi mapping to achieve your split but to write it to a file, you will have to call the file adapter for each split which you can not do without using BPM. In BPM, for each split that you perform, you can use a send step in for-each loop which will give you the functionality you require.
    Award if helpful,
    Sarath.

  • Failed to load XML file with Content ID 'XYZ'

    Hello,
    We are using UCM Version:11.1.1.8.1DEV-2014-01-06 04:18:30Z-r114490 (Build:7.3.5.185) with site studio for creating templates and web sites.
    While switching to contribution mode, we find 'Failed to load XML file with Content ID 'XYZ' error.[Here XYZ is the local checkin content]
    In region we are using dynamic converter to convert the style of native document here below are region and its element details.
    <region  id="region3" name="Add_Content_Here" flags="1111111100100" metadata="xIdcProfile%3AisHidden%3Dtrue%26xTemplateType%3AisHidden%3Dtrue%26xShowInStaff%3AisHidden%3Dtrue%26xShowInVisitors%3AisHidden%3Dtrue%26xShowInFaculty%3AisHidden%3Dtrue%26xDiscussionCount%3AisHidden%3Dtrue%26xDiscussionType%3AisHidden%3Dtrue" dccommand="ssIncDynamicConversionByRule(SS_DATAFILE, 'Colleges_Template_Rule')">
          <!--$region3_ACTIONS="EIMPRS",region3_DCCOMMAND="ssIncDynamicConversionByRule(SS_DATAFILE, 'Colleges_Template_Rule')" -->
          <element  id="region3_element1" name="Editor" label="Editor" type="1" flags="111111111111111111111100000111100000000000001111001110111010001111101000000000000000000000000000">
            <!--$region3_element1="Add_Content_Here/Editor" -->
            <linktoregioncontent  createnewxml="true" createnewnative="false" choosemanaged="true" chooselocal="false" choosenone="false">
              <choosemanagedquerytext  corecontentonly="FALSE">
                <![CDATA[xWebsiteObjectType <Matches> `Data File` <OR> xWebsiteObjectType <Matches> `Native Document`]]>
              </choosemanagedquerytext>
            </linktoregioncontent>
          </element>
          <switchregioncontent  createnewxml="true" createnewnative="true" choosemanaged="true" chooselocal="false" choosenone="false">
            <createnewnativedoctypes >
              <![CDATA[.doc,.docx,.txt,.rtf]]>
            </createnewnativedoctypes>
            <choosemanagedquerytext  corecontentonly="FALSE">
              <![CDATA[xWebsiteObjectType <Matches> `Data File` <OR> xWebsiteObjectType <Matches> `Native Document`]]>
            </choosemanagedquerytext>
            <defaultmetadata >
              <![CDATA[xIdcProfile%3AisHidden%3Dtrue%26xTemplateType%3AisHidden%3Dtrue%26xCollegesList%3AisHidden%3Dtrue%26xShowInStudents%3AisHidden%3Dtrue%26xShowInStaff%3AisHidden%3Dtrue%26xShowInVisitors%3AisHidden%3Dtrue%26xShowInFaculty%3AisHidden%3Dtrue%26xArticleSection%3AisHidden%3Dtrue%26xDiscussionCount%3AisHidden%3Dtrue%26xDiscussionType%3AisHidden%3Dtrue%26dpTriggerValue%3DCSE]]>
            </defaultmetadata>
          </switchregioncontent>
        </region>
    <!--SS_BEGIN_OPENREGIONMARKER(region3)--><!--$SS_REGIONID="region3"--><!--$include ss_open_region_definition --><!--SS_END_OPENREGIONMARKER(region3)-->
    <!--SS_BEGIN_ELEMENT(region3_element1)--><!--$ssIncludeXml(SS_DATAFILE,region3_element1 & "/node()")--><!--SS_END_ELEMENT(region3_element1)-->
    <!--SS_BEGIN_CLOSEREGIONMARKER(region3)--><!--$include ss_close_region_definition --><!--SS_END_CLOSEREGIONMARKER(region3)-->
    Regardrs,
    Syed

    Hi Syed ,
    Add the following trace sections :
    requestaudit,sitestudio*,system + Full verbose tracing
    Clear the server output .
    Replicate the same steps and once error shows up , refresh server output and copy the logs to a text file and upload here .
    Thanks,
    Srinath

  • How to validate an XML file with XSD Schema on JDK 1.4

    Hi
    I'm looking for samples how to validate xml files with xsd schema using jsdk 1.4
    Thank you.

    This is how.
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.dom.DOMResult;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.validation.Schema;
    import javax.xml.validation.SchemaFactory;
    import javax.xml.validation.Validator;
    DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
    dbfac.setNamespaceAware(true);
    SchemaFactory factory1 = SchemaFactory
                        .newInstance("http://www.w3.org/2001/XMLSchema");
    Schema schema = factory1.newSchema(new File("person.xsd"));
    dbfac.setSchema(schema);
    DocumentBuilder dbparser1 = dbfac.newDocumentBuilder();
    Document doc1 = dbparser1.parse(new File("person.xml"));
    Validator validator1 = schema.newValidator();
    DOMSource dm1 = new DOMSource(doc1);
    DOMResult domresult1 = new DOMResult();
    validator1.validate(dm1, domresult1);

Maybe you are looking for

  • Web-Service Proxy and Web-Service Client access in a Bean (EJB 3.0)

    Hello Community, i want to access the SAP Knowledge-Management via the Webservice "RepositoryFrameworkWS", which resides on our Portal-System, from my Java-Application, which runs on a NW CE 7.11 Ehp1 Java Server. I choosed to create a WS-Client as a

  • Open Office File Conversion Trick

    I have several NeoOffice files that have the odt extension. I really wanted to have access to them on my iPad without having to convert every single file. Here is a simple solution that has been working for me. I could also have uploaded them all to

  • How do I remove the padlock from my mailbox so that I can receive mail?

    We recently got a new computer and our mail server was changed from outlook express to Thunderbird. For some reason there is a padlock on our mail page, and is not allowing mail to come in from our provider oct.net. when we click the padlock it takes

  • Invoice verification print out

    Helo SAP Experts, How to take Invoice verification Prinout in mm? thanks babu

  • Hierarchial query returns ex-employees

    I have query that was developed from the similar queries I've found on various sites. It display the hierarchy starting from our board of directors in a descending manner. The problem is that the query is pulling our "Ex-employees" which are identifi