Adding a DOM node with java parser

Hi,
I am trying to add a node like
<dev_id>001</dev_id> to the following doc:-
<device_tag>
<lot_num>124643</lot_num>
<op_num>852652</op_num>
</device_tag>
so that it becomes:-
<device_tag>
<dev_id>001</dev_id>
<lot_num>124643</lot_num>
<op_num>852652</op_num>
</device_tag>
I created an XMLElement from nodefactory, created a text node of XMLText type from nodefactory and then did a appendchild on the XMLText to the element to get the
<dev_id>text</dev_id> XMLElement type.
But I can't add this element to the "device_tag" node (as shown above) as XMLNode takes only a node type for appendchild and not an XMLElement type.
Can you tell me how to do this or give an example of how to add a new element/Node to an existing Node.
thanks
Raj Basu
null

Try casting.
Also, if you want to insert an element,
use insertBefore instead of appendChild().

Similar Messages

  • What will happen if adding a new node with current cluster, while new node's CPU is slower quality?

    Hello,
    Say, I have a 3 nodes RAC, I want to add a new node to current cluster... while the new node's CPUs are slower than the others.. what will happen?
    (my concern is : can I add this new node successfully? if yes, can it anyway improve the whole cluster performance or not?)
    Thank you
    s9225

    Also you can refer MOS note : RAC: Frequently Asked Questions (Doc ID 220970.1)
    Can I have different servers in my Oracle RAC? Can they be from different vendors? Can they be different sizes?

  • Need help Adding Account (dDocAccount) programmatically with Java API

    Using Content Server Version:10.1.3.3.3 (080807) (Build:7.2.2.188)
    I am trying to create a routine using the the CIS JavaDoc as a reference, to create a programmatic way to add security Accounts. Here is a code snippet that I have:
    // Get the user API
    ISCSUserAPI api = getClient().getUCPMAPI().getActiveAPI().getUserAPI();
    ISCSUserAccount ua = api._createAccount();
    ua.setName("MY-TEST");
    I thought this would work. I don't get an error, but the dDocAccount is not created in the DOCUMENTACCOUNTS table? Is the better solution to simply add entries directly into the table?
    Thanks, Ken

    I had also posted a similar question on the intradoc group in Yahoo and received several helpful replies. The document services_reference_10gr3en.pdf provides the references to all the services, and a little bit of java code was used to call these services.
    For those interested in the code:
              // Get the Administrative API
              // ISCSUserAPI api = getClient().getUCPMAPI().getActiveAPI().getUserAPI();
              ISCSAdministrativeAPI api = getClient().getUCPMAPI().getActiveAPI().getAdministrativeAPI();
              // ISCSServerResponse sr = api.executeIDCService(ISCSContext SCSContext, java.lang.String serviceName, java.util.Map arguments);
              ISCSServerResponse sr = api.executeIDCService(getSCSContext(), commandName, arguments);
    Basically using the same base from the examples available in the CIS SDK.
    Thanks, Ken

  • Saxon and Supplied NodeList contains non-Saxon DOM Nodes error

    Hi all,
    I am writing an extension function for my xslt. So far, it was working fine, but since I switched from xalan to saxon, my function is giving me the following error:
    Supplied NodeList contains non-Saxon DOM Nodes
    I understand that I can not use non-saxon DOM nodes with saxon. The question is, how would I construct a saxon DOM objects???
    my function looks like this:
    public static NodeSet splitPortsAndResults(String portList, String resultList) {
    // in here I am creating a document and node set to be returned to my xsl
    I can not find any documentation on how to create a document using saxon.
    I have spent a lot of time researching this. I would greatly appreciate any help.
    Namrata

    Dr. Clap,
    Thanks again!!! I have been looking for this information for atleast two days. Wow! I have printed the pages that explain how to return NodeList. I will implement it on Monday or Tuesday and will let you know by Wednesday. It should be pretty straight forward.
    Again, you are the best!!!
    Namrata

  • Adding node in navigator for new extension (with Java backing class)

    Hi,
    I want to add a node to the Navigator window that is implemented by my own Java class.
    I can already add a node with XML that executes queries against the database to get the objects that I want.
    I now want a "smarter" node that can do more than query the database.
    Regards,
    Pieter

    Hi Sue,
    I have already looked on the wiki and there is no information on how to add an own node with a Java class.
    There is an example of how to do this with XML and encoding the node and children with SQL embedded in the XML.
    This is not what I want - as I mentioned in the post I have already done this but I want to do more by adding my own Java Node object.
    Regards,
    Pieter

  • Add new nodes to IDoc in IDoc-XML Schema Mapping with Java

    Hello everyone, I'm not very sure if this is the right forum but I have a problem and I haven't being able to find the answer, my scenario is as follows:
    -First of all our system characteristics: SAP ECC 6.0, SAP BASIS 700, PI BASIS 2005-1-700 and SAP APPL 600
    -We are in Mexico and we are creating our own billing documents with digital signature and a digital certificate in XML format according to SAP Note 1303712 and all derived notes.
    -Our actual schema is working fine: We generate our IDocs (one for SD and one for FI) in SAP and we send them to PI XI to be parsed by a JAVA program and then converted to XML.
    Now we have the requirement to add new nodes (I might be wrong in the term, feel free to correct me) to the IDoc, it sounds very simple but I have only experience with ABAP  and no experience with PI, also it's working only on our production landscape, so if I don't do it right it could be very dangerous.
    I have already read the following notes that might help me: 1321680 and 1318342 but their configuration is just in the aplication server and don't mention anything about PI or the Java program.
    So, if any one could provide me some kind of guide or important aspects that I should take care (like mapping, structures, etc) to enhance IDocs for this schema i would be very grateful.
    I hope this post were clear enough, if it is not also feel free to ask me to clarify or provide more information.
    Kind Regards
    Omar

    Hi Omar,
    Since the structure of the IDoc is changing (adding a new node), you would need to do the following in PI:
    1) Reimport the IDoc in ESR/IR of PI.
    2) Change the mapping/transformation logic in the mapping parser defined. If it is a Java code, you would need to reimport it in the ESR/IR. Use link below to understand more on jave mapping.
    http://wiki.sdn.sap.com/wiki/display/XI/BeginnersguidetoJavamappingusingDOMparserinSAPXI
    3) Delete the IDoc cache using transaction IDX2, after the IDoc is reimported.
    Regards,
    Sanjeev.

  • Wrong XML parsing in Java  6.0 , the same code works fine with Java 5.0

    I have the following xml data in a file ( C:\_rf\jrebug.xml ) :
    <?xml version="1.0" encoding="UTF-8"?>
    <rs>
         <data
              input3='aa[1]'
              input4='bb[1]'
              input6='cc[2]'
              input8='dd[7]'
              output2='ee[7]'
              output4='ff[511]'
              output6='gg[15]'
              output7='hh[1]'
         />
    </rs>
    I have the following code to parse this XML data :
    import java.io.IOException;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.NamedNodeMap;
    import org.w3c.dom.NodeList;
    import org.w3c.dom.Node;
    import org.xml.sax.SAXException;
    import org.xml.sax.ErrorHandler;
    import org.xml.sax.SAXParseException;
    public class DomParserBug {
         Document dom;
         public void runExample() {
    parseXmlFile("C:\\_rf\\jrebug.xml");
              parseDocument();
         private void parseXmlFile(String filename){
              //get the factory
              DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
              //dbf.setValidating(true);
    dbf.setValidating(false);
              try {
                   //Using factory get an instance of document builder
                   DocumentBuilder db = dbf.newDocumentBuilder();
                   db.setErrorHandler(new MyErrorHandler());
                   //parse using builder to get DOM representation of the XML file
                   dom = db.parse(filename);
              }catch(ParserConfigurationException pce) {
                   pce.printStackTrace();
              catch(SAXParseException spe) {
                   spe.printStackTrace();
              catch(IOException ioe) {
                   ioe.printStackTrace();
              catch(SAXException se) {
                   se.printStackTrace();
    private void parseDocument()
    Element docEle = dom.getDocumentElement();
    NodeList nl = docEle.getElementsByTagName("data");
    if(nl != null && nl.getLength() > 0)
    for(int i = 0 ; i < nl.getLength();i++)
    Element el = (Element)nl.item(i);
    NamedNodeMap attrsssss = el.getAttributes();
    for (int ii=0; ii<attrsssss.getLength(); ++ii)
    Node attr = attrsssss.item(ii);
    System.out.println("Attribute name is =" attr.getNodeName() " AND Attribute value is ="+attr.getNodeValue());
         public static void main(String[] args){
              DomParserBug dpe = new DomParserBug();
              dpe.runExample();
         class MyErrorHandler implements ErrorHandler {
              public void error(SAXParseException e) {
              System.out.println("error : " +e.toString());
         // This method is called in the event of a non-recoverable error
         public void fatalError(SAXParseException e) {
         System.out.println("fatalError : " +e.toString());
         // This method is called in the event of a warning
         public void warning(SAXParseException e) {
         System.out.println("warning : " +e.toString());
    The parsed output is :
    Attribute name is =input3 AND Attribute value is =aa[1]
    Attribute name is =input4 AND Attribute value is =bb[1]
    Attribute name is =input6 AND Attribute value is =cc[2]
    Attribute name is =input8 AND Attribute value is =dd[7]
    Attribute name is =output2 AND Attribute value is =ee[7]
    Attribute name is =output4 AND Attribute value is =ff[511]
    Attribute name   is  =output6 AND Attribute value  is =hh[1]]
    Attribute name   is  =output7 AND Attribute value  is =hh[1]
    THE LAST TWO LINES ARE SIMPLY WRONG.
    With java 5.0 the last two lines are parsed correctly :
    Attribute name   is  =output6 AND Attribute value  is =gg[15]
    Attribute name   is  =output7 AND Attribute value  is =hh[1]
    I have seen this issue only after I upgraded to java 6.0. I have searched the java 6.0 bug database but there is nothing there.
    I have also submitted a bug to the bugdatabase last month but have not heared anything.
    Anybody have any clue about this ???
    Thanks
    Edited by: skaushik on Jan 4, 2008 12:40 AM
    Edited by: skaushik on Jan 4, 2008 6:38 PM

    I have seen similar issue. I found that if you remove the square brackets from the first line in teh XML file, the last two lines are parsed correctly.
    Replace the follwing line : :
    Attribute name is =input3 AND Attribute value is =aa[1]
    with :
    Attribute name is =input3 AND Attribute value is =aa
    and the output is CORRECT :
    Attribute name is =input3 AND Attribute value is =aa
    Attribute name is =input4 AND Attribute value is =bb[1]
    Attribute name is =input6 AND Attribute value is =cc[2]
    Attribute name is =input8 AND Attribute value is =dd[7]
    Attribute name is =output2 AND Attribute value is =ee[7]
    Attribute name is =output4 AND Attribute value is =ff[511]
    Attribute name   is  =output6 AND Attribute value  is =gg[15]
    Attribute name   is  =output7 AND Attribute value  is =hh[1]

  • Implementing DOM Interface with existing Java classes

    I had planned on using some tree-like Java classes as a Document Object Model, which would give me access to all sorts of XML and DOM tools like parsers and XSLT transformers. Initially, I thought all that would be neccessary is to implement all the DOM Interfaces in org.w3c.dom and then I would have a set of classes that conformed to DOM Level 1. It was my understanding that interfaces such as DOMImplementation and Document would interface with various XML tools, allowing creation of a class that implements Document and then Document would have its various factory methods that know how to create the various DOM nodes such as Element, Attr, Text, NamedNodeMap, NodeList, etc.
    The problem I'm seeing now is that the JAXP specification (which is what the latest Xerces and Xalan tools conform to) has something called a DocumentBuilder and DocumentBuilderFactory that appear to be necessary to tell the framework what type of class to instantiate that implements the Document DOM interface. Those appear to have a lot of methods that deal with parsing of XML documents and I didn't really want to write or even subclass any existing Parsers in order to get the functionality of traversing and transforming a set of classes that implement the DOM interface.
    Am I missing something here? Is it possible to plug in any (set of classes for) DOMImplementation and get them to work with the various DOM and XML tools out there?
    Is there an easier way to allow parts of an application access to internal data structures but have the more generic tools or APIs, such as XSL transformers, access that same set of classes as a DOM with the generic DOM interface methods?
    Can someone provide me with some guidance here? I'm in the process of finalizing some design on a system and need to know if this is possible or if I need to alter my design.
    Thanks.

    If I understand you correctly, I think I am working on a similar issue. I am unhappy with the methods given by the DOM for retrieving data from the XML file and for building a file. Our software has a bunch of code that uses these classes and it is extremely ugly. My solution was to create a facade on top of the DOM model. Essentially I have some simple classes that store all the pertinent info (for me) about the XML structure. Essentially that is the element or attribute name, its values and in the case of the element, it's children. This makes it easier for me to build and retreive the data. What I then built was a loader class and a builder class. The loader takes an XML file and parses it in using the DOM classes and builds a structure using my classes and returns the root element. The builder takes a root element and creates a DOM object out of it. This frees me of having to code around the DOM classes all over the place and makes it simple to upgrade our XML code if the DOM changes or a better DOM is released. I am using factories to facilitate this and allow me to have loaders for specific types of XML documents so that I can have a class for each which further simplifies the XML related tasks of other developers on my team.

  • Problems with Java DOM Mapping

    Hi Experts,
    as part of my diploma-thesis I have to write a java DOM-Mapping, which mapps the following incoming message:
    <mt_MappingOUT>
    <set>
    <set_Element_01>...</set_Element_01>
    <set_Element_02>... </set_Element_02>
    <set_Element_03>... </set_Element_02>
    <set_Element_10>  </set_Element_10>
    </set>
    </mt_MappingOUT>
    to the following outgoinig message:
    <mt_MappingIN>
    <TABLE>
    <item>
    <item_FIELD_01>  </item_FIELD_01>
    <item_FIELD_10>  <item_FIELD_10>
    <i/tem>
    </TABLE>
    </mt_MappingIN>
    I am not a very experienced Java-Developer. You can see my code down there, which I tried to implement according to some bloggs; unfortunately the result is not what I want to have
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.Map;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.transform.Transformer;
    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;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.w3c.dom.Text;
    import org.xml.sax.SAXException;
    import com.sap.aii.mapping.api.StreamTransformation;
    import com.sap.aii.mapping.api.StreamTransformationException;
    public class DOMMAPPING implements StreamTransformation{
         public static void main(String[] args) throws Exception
              try
                   FileInputStream fin =
                        new FileInputStream("C:/mt_MappingOut.xml");
                   FileOutputStream fout =
                        new FileOutputStream("C:/target.xml");
                   DOMMAPPING mapping = new DOMMAPPING();
                   mapping.execute(fin, fout);
              catch (Exception e)          {
                   e.printStackTrace();
    public void setParameter (Map param) {}
    public void execute (InputStream in, OutputStream out)
         throws com.sap.aii.mapping.api.StreamTransformationException {
              DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
              Document documentIn = null;
              DocumentBuilder builder = null;
              try {
                        builder = factory.newDocumentBuilder();
                   } catch (ParserConfigurationException e1) {
                        e1.printStackTrace();
              try {
                   Element itemNode = null;
                   NodeList[] list_f=new NodeList[10];
                   Element[] field=new Element[10];
                   documentIn = builder.parse(in);
                   Document documentOut = builder.newDocument();
                   Element rootNode = documentOut.createElementNS("urn:agrp:xi:geissseb","ns0:mt_MappingIn");
                   documentOut.appendChild(rootNode);
                   Element tableNode = documentOut.createElement("TABLE");
                   rootNode.appendChild(tableNode);
                   NodeList list_Set=documentIn.getElementsByTagName("set");
                   System.out.println(list_Set.getLength());
                   for(int j=1;j<10;j++){
                        list_f[j-1]=documentIn.getElementsByTagName("set_ELEMENT_01"+j);
                list_f[9]=documentIn.getElementsByTagName("set_ELEMENT_10");
                   //NodeList list_f01=documentIn.getElementsByTagName("f01");
                   for (int i=0;i<list_Set.getLength();i++)
                        itemNode=documentOut.createElement("item");
                        tableNode.appendChild(itemNode);
                        for(int k=0; k<10;k++){
                             Node f=list_f[k].item(i);
                             f=f.getFirstChild();
                             String str_f=f.getNodeValue();
                             Text text_f=documentOut.createTextNode(str_f);
                             field[k]=documentOut.createElement("item_FIELD_"(k1));
                             field[k].appendChild(text_f);
                             itemNode.appendChild(field[k]);
                   TransformerFactory tf = TransformerFactory.newInstance();
                   Transformer transform = tf.newTransformer();
                   transform.transform(new DOMSource(documentOut), new StreamResult(out));
                   } catch (SAXException e2) {
                        e2.printStackTrace();
                   } catch (IOException e2) {
                        e2.printStackTrace();
                   }catch (Throwable t) { throw new StreamTransformationException("error", t); }
    Unfortunately there seems to be at least one error in there because the result I get is just the following:
      <?xml version="1.0" encoding="UTF-8" standalone="no" ?>
    - <ns0:mt_MappingIn xmlns:ns0="urn:agrp:xi:geissseb">
      <TABLE />
      </ns0:mt_MappingIn>
    Below you will find my source message:
    <?xml version="1.0" encoding="UTF-8" ?>
    - <xsd:schema targetNamespace="urn:agrp:xi:geissseb" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:agrp:xi:geissseb">
      <xsd:element name="mt_MappingOut" type="dt_MappingOut" />
    - <xsd:complexType name="dt_MappingOut">
    - <xsd:annotation>
      <xsd:appinfo source="http://sap.com/xi/TextID">a7a28830bebf11dc81aa001a4b0af224</xsd:appinfo>
      </xsd:annotation>
    - <xsd:sequence>
    - <xsd:element name="Set">
    - <xsd:annotation>
      <xsd:appinfo source="http://sap.com/xi/TextID">0b366510aeda11dcb3bb00174205b856</xsd:appinfo>
      </xsd:annotation>
    - <xsd:complexType>
    - <xsd:sequence>
    - <xsd:element name="f01" type="xsd:string">
    - <xsd:annotation>
      <xsd:appinfo source="http://sap.com/xi/TextID">0b366511aeda11dcaf2600174205b856</xsd:appinfo>
      </xsd:annotation>
      </xsd:element>
    - <xsd:element name="set_ELEMENT_02" type="xsd:string">
    - <xsd:annotation>
      <xsd:appinfo source="http://sap.com/xi/TextID">0b366512aeda11dc84d400174205b856</xsd:appinfo>
      </xsd:annotation>
      </xsd:element>
    - <xsd:element name="set_ELEMENT_03" type="xsd:string">
    - <xsd:annotation>
      <xsd:appinfo source="http://sap.com/xi/TextID">0b366513aeda11dcbcab00174205b856</xsd:appinfo>
      </xsd:annotation>
      </xsd:element>
    - <xsd:element name="set_ELEMENT_04" type="xsd:string">
    - <xsd:annotation>
      <xsd:appinfo source="http://sap.com/xi/TextID">0b366514aeda11dc96a300174205b856</xsd:appinfo>
      </xsd:annotation>
      </xsd:element>
    - <xsd:element name="set_ELEMENT_05" type="xsd:string">
    - <xsd:annotation>
      <xsd:appinfo source="http://sap.com/xi/TextID">0b366515aeda11dca77700174205b856</xsd:appinfo>
      </xsd:annotation>
      </xsd:element>
    - <xsd:element name="set_ELEMENT_06" type="xsd:string">
    - <xsd:annotation>
      <xsd:appinfo source="http://sap.com/xi/TextID">0b366516aeda11dc8f7d00174205b856</xsd:appinfo>
      </xsd:annotation>
      </xsd:element>
    - <xsd:element name="set_ELEMENT_07" type="xsd:string">
    - <xsd:annotation>
      <xsd:appinfo source="http://sap.com/xi/TextID">0b366517aeda11dcc24b00174205b856</xsd:appinfo>
      </xsd:annotation>
      </xsd:element>
    - <xsd:element name="set_ELEMENT_08" type="xsd:string">
    - <xsd:annotation>
      <xsd:appinfo source="http://sap.com/xi/TextID">0b366518aeda11dc92cd00174205b856</xsd:appinfo>
      </xsd:annotation>
      </xsd:element>
    - <xsd:element name="set_ELEMENT_09" type="xsd:string">
    - <xsd:annotation>
      <xsd:appinfo source="http://sap.com/xi/TextID">0b366519aeda11dcc9b100174205b856</xsd:appinfo>
      </xsd:annotation>
      </xsd:element>
    - <xsd:element name="set_ELEMENT_10" type="xsd:string">
    - <xsd:annotation>
      <xsd:appinfo source="http://sap.com/xi/TextID">0b36651aaeda11dcc5a700174205b856</xsd:appinfo>
      </xsd:annotation>
      </xsd:element>
      </xsd:sequence>
      </xsd:complexType>
      </xsd:element>
      </xsd:sequence>
      </xsd:complexType>
      </xsd:schema>
    When I had problems withe Java SAX Mapping, I got great hints in the forum. So I hope you can help me out again...
    Cheers Sebastian

    Here you go.
    Code
    package com.sap.test;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.Map;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import org.apache.crimson.tree.TextNode;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.w3c.dom.Text;
    import org.xml.sax.SAXException;
    import com.sap.aii.mapping.api.StreamTransformationException;
    public class DomTest {
         Document documentOut = null;
         public static void main(String[] args) throws Exception
         try
         FileInputStream fin =      new FileInputStream("test.xml");
         FileOutputStream fout = new FileOutputStream("test_out.xml");
         DomTest mapping = new DomTest();
         mapping.execute(fin, fout);
         catch (Exception e) {
         e.printStackTrace();
         public void setParameter (Map param) {}
         public void execute (InputStream in, OutputStream out)
         throws com.sap.aii.mapping.api.StreamTransformationException {
         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
         Document documentIn = null;
         DocumentBuilder builder = null;
         try {
         builder = factory.newDocumentBuilder();
         } catch (ParserConfigurationException e1) {
         e1.printStackTrace();
         try {
         Element itemNode = null;
         //NodeList[] list_f=new NodeList10;
         //Element[] field=new Element10;
         documentIn = builder.parse(in);
         documentOut = builder.newDocument();
         Element rootNode = documentOut.createElementNS("urn:agrp:xi:geissseb","ns0:mt_MappingIn");
         rootNode.setAttribute("xmlns:ns0", "urn:agrp:xi:geissseb");
         documentOut.appendChild(rootNode);
         Element tableNode = documentOut.createElement("TABLE");
         rootNode.appendChild(tableNode);
         NodeList list_Set = documentIn.getElementsByTagName("set");
         System.out.println(list_Set.getLength());
         for(int j = 0 ; j < list_Set.getLength() ;j++){
              Element setNode = (Element)list_Set.item(j);
              NodeList children = setNode.getChildNodes();
              for(int index = 0; index < children.getLength(); index++)
                   Node child = children.item(index);
                   if (child instanceof Element) {
                        Element element = (Element) child;
                        if(element.getNodeName().startsWith("set_ELEMENT"))
                             createItemFeildNode(tableNode,element);
         //list_f[9]=documentIn.getElementsByTagName("set_ELEMENT_10");
    //     NodeList list_f01=documentIn.getElementsByTagName("f01");
         /*for (int i=0;i<list_Set.getLength();i++)
         itemNode=documentOut.createElement("item");
         tableNode.appendChild(itemNode);
         for(int k=0; k<10;k++){
         Node f=list_f[k].item(i);
         f=f.getFirstChild();
         String str_f=f.getNodeValue();
         Text text_f=documentOut.createTextNode(str_f);
         field[k]=documentOut.createElement("item_FIELD_"(k1));
         field[k].appendChild(text_f);
         itemNode.appendChild(field[k]);
         TransformerFactory tf = TransformerFactory.newInstance();
         Transformer transform = tf.newTransformer();
         transform.transform(new DOMSource(documentOut), new StreamResult(out));
         transform.transform(new DOMSource(documentOut), new StreamResult(System.out));
         } catch (SAXException e2) {
         e2.printStackTrace();
         } catch (IOException e2) {
         e2.printStackTrace();
         }catch (Throwable t) { throw new StreamTransformationException("error", t); }
         private void createItemFeildNode(Element root, Element element) {
              String inName = element.getNodeName();
              int temp = inName.lastIndexOf('_');
              if (temp == -1)
                   return;
              String index = inName.substring(temp+1);
              String nodeName = "Item_FIELD_" + index;
              String nodeVal = element.getFirstChild().getNodeValue();
              Element newElement = documentOut.createElement(nodeName);
              Text txtNode = documentOut.createTextNode(nodeVal);
              newElement.appendChild(txtNode);
              root.appendChild(newElement);          
    Input
    <?xml version="1.0" encoding="UTF-8" ?>
    <mt_MappingOut xmlns="urn:agrp:xi:geissseb" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:agrp:xi:geissseb file:/D:/Eclipse/workspace/SDN/test.xsd">
    <set xmlns="">
      <set_ELEMENT_01>E1</set_ELEMENT_01>
      <set_ELEMENT_02>E2</set_ELEMENT_02>
      <set_ELEMENT_03>E3</set_ELEMENT_03>
      <set_ELEMENT_04>E4</set_ELEMENT_04>
      <set_ELEMENT_05>E5</set_ELEMENT_05>
      <set_ELEMENT_06>E6</set_ELEMENT_06>
      <set_ELEMENT_07>E7</set_ELEMENT_07>
      <set_ELEMENT_08>E8</set_ELEMENT_08>
      <set_ELEMENT_09>E9</set_ELEMENT_09>
      <set_ELEMENT_10>E10</set_ELEMENT_10>
      </set>
      </mt_MappingOut>
    Output
    <?xml version="1.0" encoding="UTF-8" ?>
    <ns0:mt_MappingIn xmlns:ns0="urn:agrp:xi:geissseb">
    <TABLE>
      <Item_FIELD_01>E1</Item_FIELD_01>
      <Item_FIELD_02>E2</Item_FIELD_02>
      <Item_FIELD_03>E3</Item_FIELD_03>
      <Item_FIELD_04>E4</Item_FIELD_04>
      <Item_FIELD_05>E5</Item_FIELD_05>
      <Item_FIELD_06>E6</Item_FIELD_06>
      <Item_FIELD_07>E7</Item_FIELD_07>
      <Item_FIELD_08>E8</Item_FIELD_08>
      <Item_FIELD_09>E9</Item_FIELD_09>
      <Item_FIELD_10>E10</Item_FIELD_10>
      </TABLE>
      </ns0:mt_MappingIn>

  • Parsing XML with Java - seeking advice for method to pursue

    Hi guys
    So here's the deal: I want to parse some XML from a server, get all the data I need from it, then shunt that data to the classes that need it. However, I'm really not sure what the best way of parsing the XML is.
    I've just written a class for obtaining the file, and one for building a DOM from the XML file. But looking at org.w3c.dom in the Java API documentation (see HERE) I'll have to implement shedloads of interfaces to be able to take advantage of the DOM, and I don't even know a lot about it.
    So am I best just writing a simple parser based on regular expressions to get the data I want? There's about 5 attributes in the XML file that I need to get - 5 for each instance of the containing element. So I don't think it'll be hard to do with regular expressions.. plus even if I did decide to implement all the DOM interfaces, the only way I'd know how to do half the stuff is with regular expressions anyway. I mean, how else would you do it? How else could you match up Nodes according to the Strings you're using for the elements, attributes etc?
    I worry that a parser using regular expressions might be too slow... I'm building this as an applet to visually display information from the server. I have nothing to support those fears, I'm just not experienced enough to know whether speed would be a problem if I chose this route... I don't think it would, but really need confirmation of that suspicion being unfounded.
    Any advice would be very, very welcome, as I'm tearing my hair out at the moment, unsure what to do.

    Komodo wrote:But JDOM is not in the core class libraries, is it? So if I want to create an applet embedded into a website, am I able to get people to download that as well?
    Sorry, I don't know anything about applets.
    Komodo wrote:Everyone's advice is appreciated, but my core question remains unanswered - would using regular expressions, considering how simple and unchanging the XML files are, be a viable option in terms of speed?
    Yes! I've done more than my fair share of XML processing with REs. It's not always easy. I often wish I could just use something XPath-like. But it's certainly easy to do and would probably mean that you'd have something up and running quicker than if you spent time investigating pure XML parsing approaches.

  • Parsing XML Node with href attribute

    Hi,
    I have the following XML that has to be parsed using JSP DOM. All fine except for one. The only problem that i have is when to parsing the Node with href attribute.
    I am using the following method, and it returned with weird result
    currNode.getAttributes() ====> the result is com.sun.org.apache.xerces.internal.dom.AttributeMap@111ae04
    currNode.getNodeValue() ====> the result is null
    currNode.TextNode ===> it returned *2*
    Can anyone please let me know what did I miss here? What should I do to parse the href attribute into the jsp page?
    The below is the xml.
    <MovieList>
    <Movie href="DarkKnight.xml">
       <head>
             <Title>Batman Dark Knight</Title>
             <Genres>
                   <Genre>Action</Genre>
                   <Genre>Sci-Fi</Genre>
             </Genres>
             <Description>Movie Details here</Description>
       </head>
    </Movie>
    </MovieList>Thanks

    I am not sure what "JSP DOM" is exactly. In the W3C DOM supported since SUN Java 1.4 if you have an element node and want to access an attribute value you can simply use String href = movieElement.getAttribute("href"); You might need to cast your Node to Element first e.g.Element movieElement = (Element)currNode;

  • How to create dom treeof html page with java

    hi, all
    i met with a problem how to create dom tree of html page wih jave, that is, given a html page, how to create a dom tree of this page with java?
    thanks in advance.
    regards
    richard

    but i m using this code to create node in html file
    HTMLLIElement li = (HTMLLIElement)appHTML.createElement("LI");
    Text txt = appHTML.createTextNode(name);
    li.appendChild(txt);
    appHTML.getElementById("name").appendChild(li);
    this will display all name value which is coming from database,
    and i want to assign a hyperlink to it,
    I have id with name also so I thought that using id i will
    create javascript like
    function popup(id)
         if(id==1)
              var n1 = window.open("../list/name1.html");
         if(id==2)
              var n1 = window.open("../list/name2.html");
    this way i want to popup particular file if i can pass id value in this function
    so want hyperlink like
    name

  • 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>

  • How to read and parse a remote XML file with Java

    Hi.
    Using J2SE v1.4.2, I'd like to read and parse a remote file:
    http://foo.com/file.xml
    Is it possible with Java? I'd be extremely grateful if someone could provide me any webpage showing a very simple code.
    Thank you very much.

    How about the following?
         import java.io.InputStream;
         import java.net.URL;
         import javax.xml.parsers.DocumentBuilder;
         import javax.xml.parsers.DocumentBuilderFactory;
         import org.w3c.dom.Document;
         public static void main(String[] args) throws Exception {
              DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
              DocumentBuilder db = dbf.newDocumentBuilder();
              URL url = new URL("http://foo.com/file.xml");
              InputStream inputStream = url.openStream();
              Document document = db.parse(inputStream);
              inputStream.close();
         }-Blaise

  • Read an XML file with java: Document to Node conversion

    Hello,
    I want to read an XML file and convert data into a Node instance because I need this for an XForm application.
    My code is:
    private Node workstationType;
    public Node initModel() {
    try {
    //This one will hold the results
    Document document;
    //loading from XML File
    String fileName="C:\\documents\\iniForm.xml";
    FileInputStream inXML = new FileInputStream(fileName);
    BufferedReader in = new BufferedReader(new InputStreamReader(inXML));
    document = XMLLoader.loadFromStream(in);
    } catch (Exception e) {
    System.err.println("ERROR:" + e.getMessage());
    e.printStackTrace(System.err);
    //Create the node for the root, 'typeOfWorkstation'
    workstationType = document.getDocumentElement(); //A
    //Return the root node
    return (workstationType);
    The problem: I can convert Node instance to Document instance (line A)
    The error message is: "document cannot be resolved".
    How can I do that??
    Thank you
    Sylvain

    Here is my XMLLoader class:
    public class XMLLoader {
         public static Document loadFromStream(Reader reader) throws Exception {
              //Build a DOM document with the reader
              //prepare DOM document
              DOMImplementation impl;
              DocumentBuilder builder;
              try {
                   // Find the implementation
                   DocumentBuilderFactory factory =
                        DocumentBuilderFactory.newInstance();
                   factory.setNamespaceAware(false);
                   factory.setValidating(false);
                   builder = factory.newDocumentBuilder();
                   impl = builder.getDOMImplementation();
                   //Read and parse the XML input stream into a DOM document
                   Document document = builder.parse(new InputSource(reader));
                   return document;
              } catch (IOException ex) {
                   throw new RuntimeException(
                        "[XMLLoader.loadFromFile]: Failed loading the InputStream. Root cause: \n"
                             + ex);
              } catch (Exception ex) {
                   throw new RuntimeException(
                        "[XMLLoader.loadFromFile]: Failed to initialize DOM factory. Root cause: \n"
                             + ex);

Maybe you are looking for

  • Issue in JSF2.0 with NetBeans6.9

    Hi, I am trying to build one jsf component using the JSF2.0 with NetBeans 6.9. I am trying to follow the steps mentioned at below link http://www.exadel.com/tutorial/jsf/HowToWriteYourOwnJSFComponents.pdf I am facing following exceptions while runnin

  • Getting the standard Notes App for Mac

    My ipad and iphone have the notes app. How do i get notes on my Mac? It is not available in the Mac AppStore and I can not find it among the apps included with the Mac. I have Mobile Me but I can't sync my notes only the contacts and calendar.?

  • Connection roll back error

    Hi, I have a problem. I am using JSF1.1, EJB2.x, JDBC and weblogic8.1sp6. the structure of the application is like this, jsf bean calls facade bean(which is stateless session bean) method. facade bean method calls dao method to perform database inser

  • Rules file lodas only every 2nd row from .txt source

    I have prepared a nice rules file, now deployed on the live server. when I copy it over to my dev it stops working because it loads only every SECOND row from my .txt source. Any ideas why that might happen? (I have no rejects specified)

  • Error 1904 when installing Crystal Reports 2010 Redistributable

    Hi, I'm having trouble installing the CR 2010 Redistributable on a few machines. We've installed all the windows updates and have reinstalled all the C++ 2005 redistributables including the newer ATL update. On install, a bunch of dll's can't registe