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.

Similar Messages

  • 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

  • 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

  • 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

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

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

  • How to parse XML using SAX Parser sequencially

    I have a requirement to parse XML file sequencially. But I need to stop the parsing in-between for doing some processing.
    Let me explain with example
    I have a file with following structure.
    <InputFile>
    <Invoice>
         <InvoiceNo = "Inv1"/>
    <InvoiceDt = "12012002"/>
    </Invoice>
    <Invoice>
         <InvoiceNo = "Inv2"/>
    <InvoiceDt = "12012002"/>
    </Invoice>
    <Invoice>
         <InvoiceNo = "Inv3"/>
    <InvoiceDt = "12012002"/>
    </Invoice>
    For each Invoice node I need to process some activites. So I need to write a method which will open the XML file and parse and returns me a complete element from <invoice> to </Invoice> sequencially.
    Please let me know whther some body has solution for this.
    Manoj.

    If you're using a SAX parser then you can implement your code in the startElement(), endElement(), and characters() methods... have a look at the tutorial here:
    http://java.sun.com/xml/jaxp/dist/1.1/docs/tutorial/index.html

  • 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

  • Problem in parsing a xml string using dom parser

    i want to parse a Xml String using a Dom parser......the parse function in dom parser takes only input stream as argument.......so i made the code as
    InputStream inputstream = new StringBufferInputStream(XmlData) ;
    InputSource inputSource = new InputSource(inputstream );
    but saxexception is coming and also warning called
    "java.io.StringBufferInputStream in java.io has been deprecated"
    please help me.........

    i want to parse a Xml String using a Dom
    parser......the parse function in dom parser takes
    only input stream as argument.......This is not true of the DOM parser in Java 1.4. So you might want to get rid of your old parser and replace it by something more current. Or perhaps you are using 1.4 and you just didn't read all of the API docs.

  • How to manipulate object mapping runtime using DOM parser in java?

    Scenario: We will be getting logical name of the table from which we have to fetch the details. We have few tables which have more or less same columns, the only difference is the prefix. Say we have Tables: Temp1 and Temp2 contains column as Temp1Col1 and Temp2Col1. I dont want to go with creating as many POJO classes in java as that of tables. So i will create only one POJO class with common attributes and at runtime i want to change the object mapping file of Hibernate to hold table values. I have an idea that this can be done using DOM parser. But it would be great if somebody can share the java code for the same.
    Thanks in advance.

    SAX is a parser, not a generator.Well,
    you can use it to create an XML file too. And it will take care of proper encoding, thus being much superior to a normal textwriter:
    See the following code snippet (out is a OutputStream):
    PrintWriter pw = new PrintWriter(out);
          StreamResult streamResult = new StreamResult(pw);
          SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance();
          //      SAX2.0 ContentHandler.
          TransformerHandler hd = tf.newTransformerHandler();
          Transformer serializer = hd.getTransformer();
          serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");//
          serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"pdfBookmarks.xsd");
          serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"http://schema.inplus.de/pdf/1.0");
          serializer.setOutputProperty(OutputKeys.METHOD,"xml");
          serializer.setOutputProperty(OutputKeys.INDENT, "yes");
          hd.setResult(streamResult);
          hd.startDocument();
          //Get a processing instruction
          hd.processingInstruction("xml-stylesheet","type=\"text/xsl\" href=\"mystyle.xsl\"");
          AttributesImpl atts = new AttributesImpl();
          atts.addAttribute("", "", "someattribute", "CDATA", "test");
          atts.addAttribute("", "", "moreattributes", "CDATA", "test2");
           hd.startElement("", "", "MyTag", atts);
    String curTitle = "Something inside a tag";
              hd.characters(curTitle.toCharArray(), 0, curTitle.length());
        hd.endElement("", "", "MyTag");
          hd.endDocument();
    You are responsible for proper nesting. SAX takes care of encoding.
    Hth
    ;-) stw

  • Generating XMLs from CSVs using DOM parser......

    Hi,
    I am trying to generate XMLs from CSV files using DOM parser. XMLs are getting generated but the problem is that i am using Encoding "ISO-8859-1" but XMLs are getting generated in UTF-8 encoding.
    Please refer to the code below and advice. (where are the code tags gone ????? )
    Source domSource = new DOMSource(document);
    ByteArrayOutputStream xmlStream = new ByteArrayOutputStream();
    Result result = new StreamResult(xmlStream);
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.transform(domSource, result);
    xmlStream.close();
    generatedXml = new String(xmlStream.toByteArray(), "*ISO-8859-1*");

    Use transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1") to specify the character set.

  • Updating XML file using DOM parser

    Hi,
    Can someone help me, how to update following XML file using DOM parser.
    The following is my XML file.
    <students>
         <student>
              <id>1</id>
              <name>abc</name>
         </student>
         <student>
              <id>2</id>
              <name>xyz</name>
         </student>
         <student>
              <id>3</id>
              <name/>
         </student>
         <student>
              <id>4</id>
              <name>ijk</name>
         </student>
         <student>
              <id>5</id>
              <name></name>
         </student>
    </students>Consider, I will input 2 fields, ie., id & name. For the matching Id, the name has to be updated.
    Though, I have achieved this, but I am unable to update the value for 3rd record, & 5th record ie., id=3 & id=5. Since, these are blank.
    Thanks.

    Some <name> elements have a child node which is a text node. From what you say it appears you know how to change those text nodes.
    The other <name> elements don't have any child nodes. But you want one. This suggests to me that you need code that creates a text node and adds it to the <name> element as its child.

  • Problem in parsing an XML using SAX parser

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

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

  • How to parse using DOM parser:

    <employee>
         <name>phaneendra</name>
         <age>21</age>
         <company>ABC</company>
         <Authorization>
              <ID>21<ID>
              <Role>Normal</Role>
         </Authorization>
    </employee>
    I am using DOM Parser.Using that parser how can i wil get the <Authorization> node value as
    <Authorization>
         <ID>21<ID>
         <Role>Normal</Role>
    </Authorization>
    thanks in advance

    Since you seem new to using DOM, I'll first give a word of advice.
    Get very familiar with the JavaDocs for things like Document, Element, Node and Attribute. There is much wisdom in those files, especially in the table near the top of the Node interface. Pay particular attention to the meaning of nodeValue for various types on content.
    Using DOM, you get a Document.
    From a Document, you can use the getDocumentElement to get the root element (in your case, the one with a name of "employee").
    From an Element, to get to a child Element with a specific name, use getElementsByTagName or getElementsByTagNameNS (if your elements are coded with NameSpaces).
    Then get the first entry in the resulting list and process it however you like.

Maybe you are looking for

  • Hp laserjet pro 200 color m251n factory reset

    My hp laserjet 200 M251n has stoppped working,  won't print and no display in LCD panel, only power light is on. I'd like to try a factory reset but the only option in the manual is via the menus and the "OK" button which of course is not working. Is

  • Backing up WD My Book Duo

    HiI want to back up My Book Duo to external drive which I connected directly to My Book Duo via USB 3.0 in the back of the device.  I want to back up only the files on My Book, is there a way to do it?Thank you.

  • Making a datagrid display properly

    I am looking for an easy solution to make the datagrid display correctly. I would assume there is a way to display the data in the order of the xml document that is being loaded. Why would the component disregard the file it is sent, doing extra work

  • Ebay photo up-loader

    The eBay photo up-loader (both of them) has stopped working in FireFox. I click on the links and nothing happens. The up-loader does work in IE.

  • Add our contact to ovi gps post office

    Dear OVI we are tnt global express iran branch want to add our contact in post office directory while ovi gps is loading tehran map iam using nokia e72 . when i use my ovi gps every things is ferfect & also our resturant name was added in the directo