Problem in parsing XML using DOM Parser.

Hi,
I am parsing an XML using DOM Parser.
When i try to get attributes of a node, i dont get in the order it is written. For Eg. This the node:
<Level0 label="News" link="/website/ing_news.nsf/ViewNewsForm?OpenForm&All" level="202" uid="COGN-4MNMT3" parentid="aaaa">
When i try to print the attribute values i should get in the order:
News, /website/ing_news.nsf/ViewNewsForm?OpenForm&All, 202, COGN-4MNMT3, aaaa
BUT I AM GETTING IN THE ORDER:
News, 202, /website/ing_news.nsf/ViewNewsForm?OpenForm&All, aaaa, COGN-4MNMT3
Is there any way to sort this problem out?
Thanks and Regards,
Ashok

Hi Guys,
Thanks a lot for your replies.
But i want to keep all the values as attributes only.
the XML file is as shown below:
<Menu>
<Level0 label="News" link="/website/ing_news.nsf/ViewNewsForm?OpenForm&All" level="202" uid="COGN-4MNMT3" parentid="aaaa" children="3">
     <Level1 label="ING News" link="" level="1" uid="COGN-4MNN89" parentid="COGN-4MNMT3" children="3" >
          <Level2 label="All ING News" link="/website/ing_news.nsf/ViewNewsForm?OpenForm&All" level="2" uid="INGD-4MVTK2" parentid="COGN-4MNN89" children="0">
          </Level2>
</Level1>
</Level0>
The code i was using to get attributes is:
String strElementName = new String(node.getNodeName());
     // System.out.println("strElementName:"+node.getNodeName());
NamedNodeMap attrs = node.getAttributes();
if (attrs != null) {
int iLength = attrs.getLength();
for (int i = 0; i < iLength; i++) {
String strAttributes = (String) attrs.item(i).getNodeName();
String strValues = (String) attrs.item(i).getNodeValue();
Also is it not possible to Enforce the order using some Schema/DTD in this case?
TIA
Ashok

Similar Messages

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

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

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

  • Convertion of flat file to XML using DOM

    Hi!
    I need help for convert a flat file to XML using DOM and by taking the validation of a specified DTD. Can any body help me in this regard.
    Bye,
    lat

    first you have to decide how the flat file will map to xml. Will you use attributes or pcdata for your fields, or both? Will there be a hierarchy, or will it be mostly flat?
    Once decided, you'd probably just use a BufferedReader to read the lines one at a time, and generate Dom nodes as appropriate, and stick them in the tree.

  • Rounding of decimal values into XML using DOM

    I want to roundoff 10.456 to 10.4(while generating the xml) using DOM.
    Please let me know how to handle this?
    Thanks in advance

    read the java.lang.Math API
    there are rounding functions there
    and next time please just use a search engine

  • How to read xml-stylesheet Processing Instruction from XML using DOM Parser

    Hi,
    I am trying to read an xml that contains xsl stylesheet PI using DOMParser. The parse() method reads the entire contents of the XML except the PI instruction. Below is the XML I am using to read
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <?xml-stylesheet href="../../../lang/en-us/style0/usc_profile.xsl" type="text/xsl"?>
    <Oblix oblang="en-us" xmlns="http://www.oblix.com/" xmlns:oblix="http://www.oblix.com/">
    <ObProfile>
    </ObProfile>
    </Oblix>
    Can anyone let me know if there are any propery settings to be done for the DOM parser before parsing?. If so, what is the property to be set?.
    Thanks in Advance
    Muthu

    A COTS product builds the XML and inserts the respective xsl (xml:stylesheet) file name to be used for transforming the xml. I am trying to interrupt this xml and make some updations on an element and finally send the updated xml to the stream.
    For the above process, I parse the input XML using DOMParser and update the elements (some internal elements). While I view the final XML that would be passed to the stream, I found the <?xml-stylesheet... PI is missing.
    I somehow managed using a temp fix by doing the below. I manually pulled the PI using document.getFirstChild().getNodeValue() and reconstructed the PI and inserted it to the outgoing XML. This needs to be done every time. This might run into problems when more than one PI is used in the XML.
    If the parsed XML could get the PI along with it the above problem could be resolved.
    Is there any property that could be set on the parser (prior to parsing) to resolve the issue?.

  • Parsing xml using DOM parser in java

    hi there!!!
    i don have much idea about parsing xml.. i have an xml file which consists of details regarding indentation and spacing standards of C lang.. i need to read the file using DOM parser in java n store each of the attributes n elements in some data structure in java..
    need help as soon as possible!!!

    DOM is the easiest way to parse XML document, google for JDOM example it is very easy to implement.
    you need to know what is attribute, what is text content and what is Value in XML then easily you can parse your document with dom (watch for space[text#] in your XML document when you parse it).
    you get root node then nodelist of childs for root then go further inside, it is easy believe me.

  • Need to retrieve all the node values of xml using DOM parser..pls help

    I want to fetch each node value in this xml file:
    <?xml version="1.0" encoding="UTF-8"?>
    <Main>
    <AAAAA>
    <ES>ESValue</ES>
    <EI>EIValue</EI>
    </AAAAA>
    <BBBBB>
    <SIP>
    <ST>STValue</ST>
    <TB>TBValue</TB>
    <PM>PMValue</PM>
    <VIP>
    <CARP>
    <AN1>AN1Value</AN1>
    <BN>BNValue</BN>
    </CARP>
    <DARP>
    <SA>
    <AN2>AN2Value</AN2>
    <CN>CNValue</CN>
    </SA>
    </DARP>
    </VIP>
    </SIP>
    </BBBBB>
    </Main>
    output should be the inner text values of diffrent nodes that contain some values..
    i.e
    output:
    ESValue
    EIValue
    STValue
    TBValue
    PMValue
    AN1Value
    BNValue
    AN2Value
    CNValue
    so that i can use thses node values and put it them in database...

    pls check the above xml file in proper redable order...I need to parse using DOM and fetch node values that are present...
    <?xml version="1.0" encoding="UTF-8"?>
    <Main>
        <AAAAA>
            <ES>ESValue</ES>
            <EI>EIValue</EI>
        </AAAAA>
        <BBBBB>
            <SIP>
                <ST>STValue</ST>
                <TB>TBValue</TB>
                <PM>PMValue</PM>
                <VIP>
                    <CARP>
                        <AN1>AN1Value</AN1>
                        <BN>BNValue</BN>
                    </CARP>
                    <DARP>
                        <SA>
                            <AN2>AN2Value</AN2>
                            <CN>CNValue</CN>
                        </SA>
                    </DARP>
                </VIP>
            </SIP>
        </BBBBB>
    </Main>

  • Update XML using DOM parser

    I am using Dom parser in java to parse xml.I am able to retrive data from xml.Can any one help me in updating an xml when data is modified in the user interface.I am created interface in html with three fields namely UserName , LastLogin, Modified fields.If Admin person wants to modify any of these three fields , those changes should reflect in xml also.
    Thanks
    divya

    Code snippet
    ===========
    OutputFormat outputFormat = new OutputFormat("XML","ISO-8859-1",true);
    outputFormat.setDoctype(null,"emp.dtd")
    It adds the DOCTYPE element but doesnt create the .DTD file.
    <!DOCTYPE ROOT_EL SYSTEM "emp.dtd">
    Any ideas?
    Rgds,
    Seetesh

  • Writing XML using DOM

    Hi All,
    I am trying to create a XML file using DOM. After creating , when I am trying to display using System.out.print , It prints [getPrice: null ]
    Here is the code.
    import org.w3c.dom.*;
    import org.apache.xerces.parsers.DOMParser;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import java.io.File;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    public class DomParseWrite
         static Document doc = null;
         static Document newdoc = null;
         public DomParseWrite( String uri )
              try
                   DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                   DocumentBuilder db = dbf.newDocumentBuilder();
                   doc = db.parse(new File( uri ) );
                   newdoc = db.newDocument();
                   createDocument();
              catch (Exception e)
                   e.printStackTrace(System.err);
         public void createDocument()
              Element newRoot = newdoc.createElement( "getPrice" );
              NodeList getPrice = doc.getElementsByTagName( "item" );
              int length = getPrice.getLength();
              for( int itemIndex = 0 ; itemIndex < length ; itemIndex++ )
                   Node first = getPrice.item( itemIndex ).getFirstChild();
                   Element item = newdoc.createElement( "item" );
                   String itemName = first.getNodeValue() ;
                   item.appendChild( newdoc.createTextNode( itemName ) );
                   newRoot.appendChild( item );
                   String priceValue = "" ;
                   if( itemName.equals( "apple" ) )
                        priceValue = "10" ;
                   if( itemName.equals( "orange" ) )
                        priceValue = "5" ;
                   Element price = newdoc.createElement( "price" );
                   Node priceVal = newdoc.createTextNode( priceValue );
                   price.appendChild( priceVal );
                   newRoot.appendChild( price );
              System.out.println( " NEw DOcument is" );
              newRoot.normalize();
              System.out.println( newRoot.toString() );
         public static void main( String args[] )
              DomParseWrite dom = new DomParseWrite( args[0] );
    Can any one tell me what is the problem.
    Regards
    Smitha

    Hi,
    I am able to compile and I cross checked if the Document is created by parsing through the nodes.
    It is creating the document properly. But problem in displaying.
    I tried with JDK1.2 and xerces on win2000. But same problem. While displaying
    System.out.println( newRoot.toString() ). it displays
    [getPrice:null].
    Regards
    Smitha

  • Comparing two XML using DOM

    Hi All,
    I am comparing two XML nodes having same nodes using DOM parser.
    <?xml version="1.0"?>
    <compare value="xml1"/>
    < test name="java">
          <compare value="xml">
              <node>012</node>
    </compare>
    </test>
    < test name="java1">
          <compare value="xml2">
              <node>013</node>
          </compare>
          <compare value="xml3">
              <node>014</node>
         </compare>
    </test>I need to take <compare> and <node> present inside <test> tag.
    I am not getting the results properly if i am using the following code
    NodeList bList1 = doc.getElementsByTagName("compare");
                        for (int temp1 = 0; temp1 < bList.getLength(); temp1++) {
                          Node nNode = bList.item(temp1);
                          NamedNodeMap attributes = (NamedNodeMap)nNode.getAttributes();
                                          for (int g = 0; g < attributes.getLength(); g++) {
                                              Attr attribute = (Attr)attributes.item(g);
                                              System.out.println(" Attribute: " + attribute.getName() +
                                              " with value " +attribute.getValue());
                                           if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                        Element eElement = (Element) nNode;
                                          NodeList nlList= eElement.getElementsByTagName("node").item(0).getChildNodes();
                    Node nValue = (Node) nlList.item(0);
                    String node = nValue.getNodeValue();
    }is there any possibility to get the <compare> and <node> tag present inside <test> tag...

    2nd xml
    <?xml version="1.0"?>
    <compare value="xml1"/>
    < test name="java">
          <compare value="xml">
              <node>012</node>
    </compare>
    </test>
    < test name="java1">
          <compare value="xml2">
              <node>015</node>
          </compare>
          <compare value="xml3">
              <node>016</node>
         </compare>
    </test>
    Map m1= new HashMap();
    NodeList bList1 = doc.getElementsByTagName("compare");
                        for (int temp1 = 0; temp1 < bList1.getLength(); temp1++) {
                          Node nNode = bList1.item(temp1);
                          NamedNodeMap attributes = (NamedNodeMap)nNode.getAttributes();
                                          for (int g = 0; g < attributes.getLength(); g++) {
                                              Attr attribute = (Attr)attributes.item(g);
    m1.put (attribute.getName(),attribute.getValue());
                                           if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                        Element eElement = (Element) nNode;
                                          NodeList nlList= eElement.getElementsByTagName("node").item(0).getChildNodes();
                    Node nValue = (Node) nlList.item(0);
                    String node = nValue.getNodeValue();
    m1.put ("node");
    Map m2= new HashMap();
    NodeList bList2 = doc1.getElementsByTagName("compare");
                        for (int temp1 = 0; temp1 < bList2.getLength(); temp1++) {
                          Node nNode1 = bLis2.item(temp1);
                          NamedNodeMap attributes = (NamedNodeMap)nNode1.getAttributes();
                                          for (int g = 0; g < attributes.getLength(); g++) {
                                              Attr attribute = (Attr)attributes.item(g);
    m1.put (attribute.getName(),attribute.getValue());
                                           if (nNode1.getNodeType() == Node.ELEMENT_NODE) {
                        Element eElement = (Element) nNode1;
                                          NodeList nlList= eElement.getElementsByTagName("node").item(0).getChildNodes();
                    Node nValue = (Node) nlList.item(0);
                    String node = nValue.getNodeValue();
    m2.put ("node");
                        List<Map.Entry<String, String>> results =
                                new ArrayList<Map.Entry<String, String>>();
                        Set<Map.Entry<String, String>> s1 = m1.entrySet();
                        Set<Map.Entry<String, String>> s2 = m2.entrySet();
                            results =
                                                        new ArrayList<Map.Entry<String, String>>();
                        for (Map.Entry<String, String> entry : s1) {
                            if (!s2.contains(entry)) results.add(entry);
                        for (Map.Entry<String, String> entry : s2) {
                            if (!s1.contains(entry)) results.add(entry);
                        System.out.println(results);Like this I am comparing :
    I need to get the attribute value of <compare> and body value for
    <node> tag and need to compare the values in both XML.

  • Remove element from xml using dom.

    i want to remove an element from an xml file using dom.
    i remove the element but the whole content of the file is also deleted.
    how can i rewrite the file.

    vij_ay wrote:
    subject :Remove element from xml,but if empty element in input file then output should be <tag></tag>, not like <tag.xml/>I assume you mean <tag/> but why do you want this? Any application that will not accept this valid XML construct is flawed and a bug report should be raised against it.

  • How to create DTD from XML using DOM

    Hi,
    Is there a way to create a corrosponding DTD of a xml-file using DOM. I have a XML-file that's pretty huge I want to create a DTD for that XML-file using DOM. Can anyone plz. lead me how to do this. I tried to use XMLSpy to convert the XML into DTD but the resulting DTD is not correct. Is there a way to create the DTD using DOM.
    Any help is really appreciated. Thanks

    When you say you are trying to convert XML to DTD, do you mean you are trying to convert a XSD (schema) to a DTD, or that you are trying to create a schema that corresponds to a given XML document.
    Realize that DTDs are not very powerful. XSD documents allow for much more detail. I don't have a proof, but I'm absolutely confident that any DTD can be expressed as a schema but not all schemas can be represented as a DTD. In other words, DTDs are not worth the trouble, in my opinion.

  • Problem in parsing an xml using DOM parser.

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

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

  • Problem in parsing XML using DOM

    I am getting one XML file as string like <?xml version="1.0" encoding="ISO-8859-1" ?> <DMSI-ACTIVITY-COMMENTS> </DMSI-ACTIVITY-COMMENTS>
    Every time I want to add new node <ACTIVITY>
              <NAME></NAME>
              <ID></ID>
              <COMMENT></COMMENT>
         </ACTIVITY> whenever user make any change in my application.
    I wrote code....
    InputStream inputStream = new ByteArrayInputStream(file.getBytes());
    Document doc = docBuilder.parse(inputStream);
    Element activityNode = doc.createElement("ACTIVITY");
    Element nameNode = doc.createElement("NAME");
    activityNode.appendChild(nameNode);
    Text nametextNode = doc.createTextNode(name);
    nameNode.appendChild(nametextNode);
    Element root = doc.getDocumentElement();
    root.appendChild(activityNode);
    String resultUDA = doc.toString();
    Problem: Here I am getting value of resultUDA is [#document: null]. I need updated XML as String....
    any one can give me suggestion or any other option to solve this issue...
    thanks in advance...

    I got it ....pls check on it
    http://www.theserverside.com/discussions/thread.tss?thread_id=26060

  • Reimporting exported XML using DOM

    Hi,
    I'm trying to set up an import/export for a data structure, 'SimpleNode' created by a JavaCC parser for classical propositional logic.
    SimpleNode implements Node, and have the following attributes
    protected SimpleNode parent;
    protected SimpleNode[] children;
    protected int id;
    protected LogicParser parser;
    protected String label;
    ...So nothing too special there.
    A simple representation of the sentence
    a OR (b AND c) IMPLIES NOT(D)
    "a | (b & c) => !d"
    Is represented as a tree with in the following manner
    Root
    Imp
      Or
       Atom a
       And
        Atom b
        Atom c
      Not
       Atom dWhich is all fine.
    I've written something to export to an XML structure which gives the following output for the above sentence
    <IMPLIES>
      <NOT>
        <TRUE/>
      </NOT>
      <IMPLIES>
        <OR>
          <ATOM>a</ATOM>
          <ATOM>b</ATOM>
        </OR>
        <NOT>
          <ATOM>c</ATOM>
        </NOT>
      </IMPLIES>
    </IMPLIES>Which again, seems fine.
    The problem is then when I'm trying to reimport the XML and create a SimpleNode from it.
    Using the following code
         public static void main(String[] args) {
              // if (args.length <= 0) {
              // System.out.println("Usage: java DOMCommentReader URL");
              // return;
              String url = "propLogic.xml";
              try {
                   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                   DocumentBuilder parser = factory.newDocumentBuilder();
                   // Check for the traversal module
                   DOMImplementation impl = parser.getDOMImplementation();
                   if (!impl.hasFeature("traversal", "2.0")) {
                        System.out.println("A DOM implementation that supports traversal is required.");
                        return;
                   // Read the document
                   Document doc = parser.parse(url);
                   // Create the TreeWalker
                   DocumentTraversal traversable = (DocumentTraversal) doc;
                   // Taken from
                   // http://www.oreilly.com/catalog/jenut2/chapter/ch19.html
                   NodeFilter filter = new NodeFilter() {
                        public short acceptNode(Node n) {
                             if (n.getNodeType() == Node.TEXT_NODE) {
                                  // Use trim() to strip off leading and trailing space.
                                  // If nothing is left, then reject the node
                                  if (((Text) n).getData().trim().length() == 0)
                                       return NodeFilter.FILTER_REJECT;
                                  // if (n.getParentNode().getNodeName() != "ATOM")
                                  // return NodeFilter.FILTER_REJECT;
                             return NodeFilter.FILTER_ACCEPT;
                   int whatToShow = (NodeFilter.SHOW_ELEMENT + NodeFilter.SHOW_TEXT);
                   TreeWalker iterator = traversable.createTreeWalker(doc, whatToShow, filter, true);
                   printElements(iterator, 0);
              } catch (SAXException e) {
                   System.out.println(e);
                   System.out.println(url + " is not well-formed.");
              } catch (IOException e) {
                   System.out.println("Due to an IOException, the parser could not check " + url);
              } catch (FactoryConfigurationError e) {
                   System.out.println("Could not locate a factory class");
              } catch (ParserConfigurationException e) {
                   System.out.println("Could not locate a JAXP parser");
         public static void printElements(TreeWalker iterator, int depth) {
              Node n = iterator.getCurrentNode();
              n.normalize();
              String indent = new String();
              for (int i = 0; i < depth; i++) {
                   indent += "  ";
              depth++;
              System.out.print(indent + n.getNodeName() + " " + n.getNodeValue());
    //          if (n.getParentNode() != null)
    //               System.out.print(" (parent is " + n.getParentNode().getNodeName() + ")");
              System.out.println();
              for (Node child = iterator.firstChild(); child != null; child = iterator.nextSibling()) {
                   printElements(iterator, depth);
              iterator.setCurrentNode(n);
         }I can get a correct looking representation of the structure
    #document null
      IMPLIES null
        NOT null
          TRUE null
        IMPLIES null
          OR null
            ATOM null
              #text a
            ATOM null
              #text b
          NOT null
            ATOM null
              #text cBut I'm having trouble using the Iterator to create SimpleNodes from the Nodes
    All a SimpleNode needs is a type (an integer representing whether the operator is AND, OR, NOT, IMPLIES etc)
    and a label, which can be null or in the case of an ATOM will have the atom name, "a", "b", "c" etc.
    A SimpleNode is easily created with the constructor
    SimpleNode foo = new SimpleNode(type);
    foo.setLabel("a");
    and adding a child by
    foo.jjtAddChild(SimpleNode n, int i)
    where i is the number of the child.
    Hopefully I've not rambled too much and it makes sense.
    If anyone can give me any pointers or some code/pseudocode to pick through then it'd be much appreciated.
    Duncan

    No bother, tweaked the printElements to fix.

Maybe you are looking for

  • How to make a single PDF file with pages for each Invoice (XML/XPD)

    I appologize, this is my first time doing this so try not to assume too much when responding. I have designed an invoice form in LiveCycle Designer and have it properly connected to an XPD feed that is dynamically created with PHP. When the user open

  • Unzip Password protected EasyDMS71SP02P_1-20006126.ZIP file

    Hi, I downloaded and am trying to unzip the SAP Easy DMS files which is password protected. Can someone please advise of the password required to unzip this file? Thanks and regards, Iqbal

  • Linking Postfix to the PostfixAdmin MySQL database

    I am building a hosting platform on OS X Server. Thus, I want to manage mail users and virtual domains in a database. First, I followed Pterobyte's advises in order to manage virtual domains with Postfix, using Apple's administration tools (http://do

  • IMovie-Problem with hangups.

    I just upgraded to IMovie 11 from IMovie 8. I only have about three short projects (15 min each) and one longer one (5 1/2 hours worth of clips) in IMovie, so it shouldn't be too slow. I had no problems with hangups working on 8, but immediately had

  • Difference between Routine & Formula

    Hi All, What is the difference between writing formula in Routine & in Formula for an InfoObject in Transfer Rules Thanks Learner