How to read an attribute of an xml tag in jsp.

hi guys,
This is murali krishna. i have a small problem,
i have one xml file (books.xml)
<?xml version="1.0" encoding="iso-8859-1"?>
<library>
<book id="1">
<name>Head First Java, 2nd Edition</name>
<author>Kathy Sierra and Bert Bates</author>
<publication-date>09-Feb-2005</publication-date>
</book>
<book id="2">
<name>Effective Java</name>
<author>Joshua Bloch</author>
<publication-date>28-May-2008</publication-date>
</book>
<book id="3">
<name>Java How to Program, 7th Edition</name>
<author>Harvey M. Deitel and Paul J. Deitel</author>
<publication-date>6-Jan-2007</publication-date>
</book>
</library>
I tried to read this xml file in jsp as shown below
<%@ page language="java" %>
<%@ page import="org.w3c.dom.*" %>
<%@ page import="javax.xml.parsers.DocumentBuilder" %>
<%@ page import="javax.xml.parsers.DocumentBuilderFactory" %>
<%
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db =dbf.newDocumentBuilder();
Document doc=db.parse("c:\\books.xml");
NodeList nl = doc.getElementsByTagName("book");
%>
<html>
<head>
<title>How to read XML file in JAVA</title>
</head>
<body>
<%
for(int i=0;i<nl.getLength();i++)
NodeList nameNlc= doc.getElementsByTagName("name");
Element nameElements=(Element)nameNlc.item(i);
String nameTagValue=nameElements.getChildNodes().item(0).getNodeValue();
NodeList authorNlc= doc.getElementsByTagName("author");
Element authorElements=(Element)authorNlc.item(i);
String authorTagValue=authorElements.getChildNodes().item(0).getNodeValue();
NodeList dateNlc= doc.getElementsByTagName("publication-date");
Element dateElements=(Element)dateNlc.item(i);
String dateTagValue=dateElements.getChildNodes().item(0).getNodeValue();
out.println("name :"+nameTagValue+"<br>");
out.println("author :"+authorTagValue+"<br>");
out.println("publication-date :"+dateTagValue+"<br><br>");
%>
</body>
</html>
so, my problem is I was unable to read the attribute of the tag book , that is "id".
can any one tell me how to read this "id" attribute.
Murali Krishna
[email protected]

hi,
U r retriving the elements by tag name.So it just chks the tag name ie.<book> & gives u array of elements.But u need retrive d attribute of <book> tag itself.
=Solution =====
Add one more statement ----> var[]= doc.getElementsByName("book");
Now u hav book elements as an array & can retrive id in for loop
for(var; var.length;var++)
doc.element[var].id.value

Similar Messages

  • How to read the attribute of the xml file using jaxb

    Thanks,
    Buddy as i have a issue i have to read the xml file using jaxb and xml file contains this data and i have read the attribute like name , desc and action for a particular menu name pls tell the code how to do this it will be a great favour to me
    thanx in advance
    Rasool
    <contextmenu>
    <menu name='Lead' >
    <menuitem name='newlead' desc='New Lead' action='/leads.do?dispatch=insert' />
    <menuitem name='editlead' desc='Edit Lead' action='' />
    <menuitem name='leadinfo' desc='Lead Information' action='' />
    </menu>
    <menu name='Cases' >
    <menuitem name='' desc='' action='' />
    <menuitem name='' desc='' action='' />
    <menuitem name='' desc='' action='' />
    </menu>
    <menu name='Contact' >
    <menuitem name='' desc='' action='' />
    <menuitem name='' desc='' action='' />
    <menuitem name='' desc='' action='' />
    </menu>
    </contextmenu>

    What my program do is to get the encoding of XML files and convert them to UTF-8 encoding files, while I need this "encoding" information of the original XML document thus I can convert...
    After reading specifications and JDOM docs, the truth turns to be disappointed, no function is provided to get this information in JDOM level 2(the current released one), while it's promissed that this function will be provided in JDOM level API....
    Thanx all for your help and attention!!!

  • How to get the attribute of the xml tag

    I have the following xml file
    Example.xml
    <?xml version="1.0" encoding="iso-8859-1"?>
    <html><set label="09/07/29" value="1241.90"/>
    </html>
    Can any one help me in parsing this xml file
    I want to retrive the attribute values of the tag set
    Example I want to store 09/07/29 to variable1 and 1241.90 to variable2 in order to insert this data into a database table.
    Appreciate if any one can help me..very urgent

    Dup post.
    Answers provided at {message:id=3658564} and {message:id=3658522}

  • How to read the attribute of a XML element? Please help!

    Hi experts,
            <Batch>
                  <BatchCode ID= AA>
                    <DeliveryNote>190098</DeliveryNote>
                    <LotQuantity>1560</LotQuantity>
                  </BatchCode>
                  <BatchCode ID= BB>
                    <DeliveryNote>190098</DeliveryNote>
                    <LotQuantity>1560</LotQuantity>
                  </BatchCode>
              </Batch>
            Target message:
                <BatchDelivery>
                  <DeliveryNote>190098</DeliveryNote>
                  <DNQuantity>1560</LotQuantity>
                </BatchDelivery>
           From the source message I want to pull only those batch details where ID is BB.
           How to handle thsi in mapping?
    Thanks
    Gopal

    Hi Prabhu,
             I ma sorry I have two levels of checks in my source XML.
    <Batch>
    <BatchCode ID= AA>
    <BatchLabel>Primary</BatchLabel>
    <DeliveryNote>190098</DeliveryNote>
    <LotQuantity>1560</LotQuantity>
    </BatchCode>
    <BatchCode ID= BB>
    <BatchLabel>Secondary</BatchLabel>
    <DeliveryNote>190098</DeliveryNote>
    <LotQuantity>1560</LotQuantity>
    </BatchCode>
    <BatchCode ID= BB>
    <BatchLabel>Primary</BatchLabel>
    <DeliveryNote>190098</DeliveryNote>
    <LotQuantity>1560</LotQuantity>
    </BatchCode>
    </Batch>
    So I need to pull batch details where first the BatchCode ID= AA and then where BatchLabel value is 'Primary'
    Target message:
    <BatchDelivery>
    <DeliveryNote>190098</DeliveryNote>
    <DNQuantity>1560</LotQuantity>
    </BatchDelivery>
    How to do the graphical mapping for this situation?
    Thanks
    Gopal

  • Read a word embedded in xml tag

    Hi everyone...
    i am an university student. i am doing a final year project.....dealing with program
    i want to ask how to read a word embedded in xml tag...
    that is e.g apple
    xml file: <fruit> apple </fruit>
    <price>$4.00</price>
    how to read apple from xml file and using a variable to store the word using java?
    pls help.....

    If you want to parse XML (more than the simple example you give), I recommend you go here: http://xml.apache.org and download Xerces for Java.
    If you want to parse the text yourself, look at:
    java.lang.String methods: indexOf(String,int) and substring(int,int)
    java.util.StringTokenizer

  • Help on how to read the content of an XML file from the payload

    I have a receiver channel / mail adapter, that sends e-mails with a XML attachment.
    I’m trying to write a Bean, that should make it possible to rename the attached XML file dynamically.
    In the Bean I want to read the content of the attached XML file, it could be the “order number”.
    The filename should then be “Order number”.XML.
    <u><i>Can anyone help me with how to read the content of the XML file from the payload.</i></u>
    <i><b>Frank</b></i>

    hi,
    check this: http://jakarta.apache.org/poi/

  • How to add attributes in the xml tag

    hi,
    i have two tables employee,department
    employee table
    empno number,
    empname varchar2(100),
    deptno number,
    department table
    deptno number,
    deptname varchar2(100)
    i want xml file in the above mentioned two tables.The xml file is as follows,
    <?xml version="1.0" encoding="UTF-8" ?>
    <EmployeeInfo>
    <Data type="employee">
    <empno>1</empno>
    <empname>siva</empname>
    <deptno>10</deptno>
    </data>
    <Data type="department">
    <deptno>10</empno>
    <deptname>IT</empname>
    </data>
    </EmployeeInfo>
    can anybody please give plsql code for this requirement.i need to add attributes in the xml tag.Its urgent
    By
    Siva

    A general example (based on the OE sample data/tables)
    SQL>SELECT XMLElement("Emp",
      2                     XMLAttributes(employee_id AS "id"
      3                                  , '10' "dept"),
      4                     first_name||' '||last_name) as result
      5 FROM   employees e
      6 WHERE  department_id = 10;
    RESULT
    <Emp id="200" dept="10">Jennifer Whalen</Emp>

  • How to read the attributes of XML file

    Hi this is ant,
    I am new to java, XML, I have a senario
    1) I have to read all the href attributes for topicref child, and then read the corresponding xml file which is mapped in href="".
    First.xml
    <map>
    <topicref nav="garage" href="task/gar/view.xml" class="..">
    <linktext class="_map/linktext">Garage</linktext>
         <topicref nav="" href="task/gar/change.xml" ..>
    <linktext class="_map/linktext">Garage</linktext>
    </topicref>
    </linktext>
    </topicref>
    </map>
    2) task/gar/view.xml file , has id attribute & need to get the id values.
    Like this I have to get the id values for all the href attributes of first xml & read correspoding id values.
    I have just read some doc using XPATH we can do, please help me.
    Thanks.
    anto

    * Try this Link, there is solution
    http://forums.sun.com/thread.jspa?messageID=9665228
    Can...Can...If we try...!

  • How to read the attribute in mapping..

    Hi,
    My source XML looks like this
    <GLDEBITACCT>
                <VALUE>0545-K-2006605-5500001</VALUE>
                <GLCOMP glorder="0">0545</GLCOMP>
                <GLCOMP glorder="1">K</GLCOMP>
                <GLCOMP glorder="2">2006605</GLCOMP>
                <GLCOMP glorder="3">5500001</GLCOMP>
      </GLDEBITACCT>
    Where glorder is the attribute of GLCOMP. Now I have requirement to read the attribute ( atleast 2 of them)
    I have to map to target field checking the value in glorder="1
    For e.g. with above XML, if the value in glorder="1 is K than map value from glorder="2 (2006605) to Target 1.
    IF the glorder="1 is P map the value in glorder="2 to Target 2 and goes on for another one
    How can i acheive this mapping. When I tried putting the value of glorder, i am not getting anything.
    Regards,

    Hi,
    You can use below UDF. Please make sure to select context parameter while creating UDF. There will be 3 input arguments for this function:
    1. GLCOMP (a)
    2 @glorder   (b)
    3 Constant   (c)  --depending upon the target node
    Also conext of attribute @glorder should be same as that of GLCOMP.
    //write your code here
    for(int i=0;i<a.length;i++)
        if(b<i>.equals("1")&&c[0].equals(a<i>))
        for(int j=0;j<a.length;j++)
              if(b[j].equals("2"))
         result.addValue(a[j].toString());
                            break;
    For target node target1 use K as 3rd argument, for target node target2 use P and so on.
    Let me know how it works.
    Regards,
    Anirudh.

  • How to read configuration data from an xml file (not web.xml)?

    Hi,
    I want to separate the application specific configuration parameters in a separate xml file and read them as and when they are needed? I know that I can use the wb.xml but I want to separate them in a different xml file because I don't want the web.xml file to be played around later after deployment. If any change is needed then it should be done in the application-config.xml.
    How can I read the parameters from this xml file in my jsp code and also what should be the location of this file if I have
    ../webapps/Root/application
    directoty structure ?
    Any help is greatly appreciated.

    can you give an example of a property file and also
    it is loaded in the jsp ?Hmm... loading properties in a JSP is not a very good idea. You should do it in a separate class, rather than mixing the logic with the display logic.
    Properties properties = new Properties();
    properties.load(UtilClass.class.getResourceAsStream("config.properties"));
    // Add a try - catch block around the load
    // for IOException...

  • How to change the attributes of an XML file

    hi peeps 'ope you can help me here i need to change the attributes of an xml file, i parse it first using a DOM parser but i cant find a way to change the attributes in the XML file, setAttribute() works only at runtime and doesn't change the attribute in the file itself. I can't find a method that will answer my question. I've searched through the forum and found similar threads....they say in order to write and change the attribute i must use the write() method of the XmlDocument class defined in com.sun.xml.tree.XmlDocument. But, i found another thread, and it says that com.sun.xml.tree.XmlDocument is not safe to use and i should use org.apache.crimson.tree.XmlDocument.....i can't find the XmlDocument class and the API for this package so i really dont know where to start...hope you guys can help me! thnx

    thanks for responding roland....i already found the solution...i didn't use the XmlDocument class because i can't find any documents about it except for JAXP 1.0 here is my code snippet...i used the TransformerFactory and Transformer class to write
    import org.w3c.dom.*;
    import org.w3c.dom.traversal.*;
    import javax.xml.parsers.*;
    import javax.xml.transform.*;
    import javax.xml.transform.dom.*;
    import javax.xml.transform.stream.*;
    Document doc = null;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    dbf.setValidating(false);
    doc = db.parse(fileGetFile); //this is the XML file
    n1 = (Node)doc.getDocumentElement();
    e1 = (Element) n1;
    NodeList nodeList = doc.getElementsByTagName ("File");
    //just insert whatever you want to do with the XML...parse it..set/change the attribute..etc....sample snippet below changes the attribute downloaded to "no"
    for(int iWriteFailed = 0; iWriteFailed <nodeList.getLength() ; iWriteFailed ++){     
    n2 = nodeList.item(iWriteFailed);
    e2 = (Element) n2;          
    e2.setAttribute("downloaded", "no");}
    try{
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.transform(new DOMSource(doc), new StreamResult ( new FileOutputStream ( fileGetFile) ) );}
    catch(Exception trans){}
    thanks for responding and keeping the information interchange alive here in the forum...
    Pau

  • How to get a text between two XML tags?

    Hello everybody!
    I've got a problem! How can I extract a text that is between tags, like <myTag> My text </myTag> I have no problem to get the attributes inside the tags, however, i don't know how to get some text that is between tags. Here is my xml:
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <tangram_request service_id="3">
    <send keep_session="nada">
    <source></source>
    <destination>3196931566</destination>
    <channel_id>2</channel_id>
    <text>Teste ServerSocket!!!</text>
    </send>
    </tangram_request>
    Now, there's a fragment of my code, which gets some tags' attributes:
    DOMParser parser = new DOMParser();
    InputSource resp = new InputSource(new StringReader(XML));
    parser.parse(resp);
    Document doc = parser.getDocument();
    Node node =(doc.getElementsByTagName "tangram_request")).item(0);
    if (node instanceof Element)
    Element el = (Element) node;
    service_id = el.getAttribute("service_id");
    System.out.println("\n\nService_id="+service_id);
    }else{System.out.println("Erro");}
    node = (doc.getElementsByTagName("send")).item(0);
    if (node instanceof Element)
    Element el = (Element) node;
    keep_session = el.getAttribute("keep_session");
    System.out.println("keep_session="+keep_session);
    }else{System.out.println("Erro");}
    Now, I want to get the texte between <destination> ... </destination>
    How could I do that?
    Thanks a lot
    Calegari

    Thanks... It worked fine!!!
    Now how can I get lots of <desctination>... I did something that haven't worked...
    node = (doc.getElementsByTagName("destination")).item(0);
    while(node.hasChildNodes())
    destination = node.removeChild(node.getFirstChild()).getNodeValue();
    System.out.println("destination="+destination);
    And now, my XML is like:
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <tangram_request service_id="3">
    <send keep_session="nada">
    <source></source>
    <destination>3196931566</destination>
    <destination>3196931567</destination>
    <channel_id>2</channel_id>
    <text>Teste ServerSocket!!!</text>
    </send>
    </tangram_request>
    Thanks so much!
    Calegari

  • How to set an attribute of a HTML tag with a value in the Servlet

    I have a HTML page and a Servlet.
    The HTML page sends a request to the Servlet.
    The Servlet has to read the contents of the HTML page. When the Servlet encounters the body tag it should set the bgcolor attribute of the body tag with a string(For eg.a string called color with a value blue) in the servlet.
    After doing this the Servlet has to update the original HTML page with the changes (in the body tag).
    I need a help on this.

    Hi sangee,
    you could get what you want to do by using a Java Server Page instead of both a HTML page and a Servlet.
    I should code something like this:
    <%Strung color="yourColor"%>
    <html><head><title></title></head>
    <body bgcolor="<%=color%>
    </body>
    </html>

  • How to get the value in the XML tag?

    hi all,
    i am new to JAXP. i tried the sample program provided in the following link. it just counts the number of tags in the XML file. XML file name is given as command line argument.
    Now, if i want to display the value in the XML tag( say <NAME>xxx</NAME> in this tag i want to display the value 'xxx' ), what has to be done?
    how can i achieve this?
    please help...
    link of the sample program:
    http://xml.apache.org/~edwingo/jaxp-ri-1.2.0-fcs/samples/SAXLocalNameCount/SAXLocalNameCount.java
    thx in advance,
    -Soni.

    implement this method the same way you have startElement...
    public void characters(char[] ch,
                           int start,
                           int length)
                    throws SAXException

  • How to find the selection character is xml tag or not?(CS2-js)

    I have a xml tagged indesign document, when i select a tag in paragraph i cant able to find it as xml tag, it only shows me the character contents as small box, is there any way to find the selected item is xml tag or not ?
    thanks
    subha

    I have a xml tagged indesign document, when i select a tag in paragraph i cant able to find it as xml tag, it only shows me the character contents as small box, is there any way to find the selected item is xml tag or not ?
    thanks
    subha

Maybe you are looking for

  • Opening Balance and closing balance

    Dear All,              Can i create a calculated field for ledger opening balance and closing balance. we are using  epicor. I dont know the exact table which captures opening balance and closing balance, where as i got credit balances and debit bala

  • Error assigning users to application Role in Obiee 11.1.1.7.0

    Hello I installed Obiee 11.1.1.7.0 both on Windows and Linux platform and after that, I successfully set Active Directory integration. I have a problem assigning users to Application Role in EM. When I'm trying to search a user on Display name, the P

  • Camera Calibration Profile in Adobe Camera Raw 5.3

    I'm trying to figure out the Camera Calibration tab in Adobe Camera Raw 5.3.  It seems that every picture I open selects a different Camera Profile in the drop down menu.  How do I know which one is appropriate for my camera (Nikon D40X)?  Or, do you

  • CENVAT clearing line missing in MIRO

    Hi Experts I have an issue in MIRO with cin posting with TAXINN. I have posted GR with incoming excise for BED, Ecess and SHEcess. This doc got posted perfectly But when i attempt MIRO, i am not getting 3 cenvat-clearing lines. Iam getting Ecess and

  • Upgrading from Solaris 10 5/08 to 10/09

    hi I need to upgrade a lab machine v210 from 5/08 to 10/09. I have mounted the 10/09 DVD on the solaris, but there is the upgrade button? No live upgrade needed or anything fancy. Regards