How To read an XML file with JDom

I have read through some tutorials after installing JDom on how to read an existing XML file and I was confused by all of them. I simply want to open an XML file and read one of the node's content. Such as <username>john doe</username> this way I can compare values with what the user has entered as their username. I am not sure were to start and I was hoping someone could help me out.
I know that this seems like an insecure way to store login information but after I master opening and writing XML files with JDom I am going to use AES to encrypt the XML files.

Here is a test program for JDom and XPath use considering your XML file is named "test.xml" :import org.jdom.input.*;
import org.jdom.xpath.*;
public class JDomXPath {
public static void main(String[] args) {
  SAXBuilder saxBuilder = new SAXBuilder("org.apache.xerces.parsers.SAXParser");
  try {
   org.jdom.Document jdomDocument = saxBuilder.build("test.xml");
   org.jdom.Element usernameNode = (org.jdom.Element)XPath.selectSingleNode(jdomDocument, "//username");
   System.out.print(usernameNode.getText());
  } catch (Exception e) {
   e.printStackTrace();
}(tested with Eclipse)

Similar Messages

  • How to read a xml file with StringReader class

    Hi,
    I need to read a XML document with StringReade class. My aplication receives an absolute path but this doesn't work:
    StringReader oStringReader =
    new StringReader(c:\java\libros.xml);
    However it works with:
    StringReader oStringReader =
    new StringReader("<?xml version="1.0" e......");
    ie, with the whole document as a String, but I need to do it as the frist way.
    Thanks

    Hi,
    I need to read a XML document with StringReade class.
    My aplication receives an absolute path but this
    doesn't work:
    StringReader oStringReader =
    new StringReader(c:\java\libros.xml);
    However it works with:
    StringReader oStringReader =
    new StringReader("<?xml version="1.0" e......");
    ie, with the whole document as a String, but I need
    to do it as the frist way.
    Thankstake a look at this link:
    http://java.sun.com/webservices/jaxp/dist/1.1/docs/tutorial/sax/2a_echo.html

  • How to read an xml file from headers

    Hi ,
    I am not getting how to read an xml file sent by client device in header to server.
    Thankx.

    There is a getHeader() in HttpServletRequest interface
    String locationURL=request.getHeader("Location");If URL of your file was set in Location attribute of header.
    Edited by: ngpgeeta on Dec 19, 2008 8:03 AM

  • I need for a simple example of  reading a xml file using jdom

    Hello
    I have been looking for a simple example that uses Jdom to read am xml file and use the information for anything( ), and I just can't find one.since I'm just beggining to understand how things work, I need a good example.thanks
    here is just a simple cod for example:
    <xmlMy>
         <table>
              <item name="first" value="123" createdDate="1/1/90"/>
              <item name="second" value="456" createdDate="1/4/96"/>
         </table>
         <server>
              <property name="port" value="12345"/>
              <property name="maxClients" value="3"/>
         </server>
    </xmlMy>Dave

    Hi,
            FileInputStream fileInputStream = null;
            try {
                fileInputStream = new FileInputStream("my_xml_file.xml");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally{
                if (fileInputStream == null) return;
            SAXBuilder saxBuilder = new SAXBuilder();
            saxBuilder.setEntityResolver(new EntityResolver() {
                public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
                    return new InputSource(new StringReader(""));
            Document document = null;
            try {
                document = saxBuilder.build(fileInputStream);
            } catch (JDOMException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (document == null) return;
            Element element = document.getRootElement();
            System.out.println(element.getName());
            System.out.println(element.getChild("table").getName());

  • How to "use" a xml file with a script?

    Hey Guys!
    I use the normal Button with the send-option to send the xml file to an url.
    My question is how it's possible to work in a php-script with the xml data out of the formular?
    Thanks for help.
    LG
    Adrian

    Hi,
    I need to read a XML document with StringReade class.
    My aplication receives an absolute path but this
    doesn't work:
    StringReader oStringReader =
    new StringReader(c:\java\libros.xml);
    However it works with:
    StringReader oStringReader =
    new StringReader("<?xml version="1.0" e......");
    ie, with the whole document as a String, but I need
    to do it as the frist way.
    Thankstake a look at this link:
    http://java.sun.com/webservices/jaxp/dist/1.1/docs/tutorial/sax/2a_echo.html

  • How do you display xml file with xlst sheet in jsp

    I have an xml file with accompanying xslt file (and several images that are used in a single directory. If I doubleclick on the xml file, it displays perfectly in my browser - Formatting, images and all!
              The 100 dollar question - How do I duplicate this behavior in a JSP page in WebLogic 8.1 using the code in the xml and the accompanying xslt (formatting) file? I tried simple embedding the xml code in the jsp, but that didn't seem to work. What is the secret?
              Okay, I need to add a bit more information here. I understand that it is really easy to just redirect to the XML file. The issue is really security. I want the XML to be inside a jsp that will only allow validated users to view it.
              Another way to look at the problem would be, can I add a jsp security tag to the xml file? Or how to I add the xml code inside a jsp and keep the path references to the xslt and graphics.
              Hope the added information helps
              Thanks,
              Ken
              Message was edited by: KLee - 20050609 10:25 MST
              [email protected]

    This proved out to be the answer. Thanks for the direction!
              import java.io.File;
              import java.io.IOException;
              import java.io.InputStream;
              import java.io.OutputStream;
              import java.io.FileNotFoundException;
              import java.io.FileOutputStream;
              import javax.servlet.ServletException;
              import javax.servlet.http.HttpServlet;
              import javax.servlet.http.HttpServletRequest;
              import javax.servlet.http.HttpServletResponse;
              import javax.xml.transform.Transformer;
              import javax.xml.transform.TransformerConfigurationException;
              import javax.xml.transform.TransformerException;
              import javax.xml.transform.TransformerFactory;
              import javax.xml.transform.stream.StreamResult;
              import javax.xml.transform.stream.StreamSource;
              public class XML_XSLT_Servlet extends HttpServlet {
              protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
                        String xmlfile = req.getParameter("xmlfile"); if (xmlfile==null) xmlfile = "test.xml";
                        String xsltfile = req.getParameter("xsltfile"); if (xsltfile==null) xsltfile = "test.xslt";
                        /* Test if file exists!, or use default file */
                        File f1 = new File(getServletContext().getRealPath("WEB-INF/displayfiles/"), xmlfile);
                        File f2 = new File(getServletContext().getRealPath("WEB-INF/displayfiles/"), xsltfile);
                   if (f1.exists() && f2.exists()) {
                             // System.out.println("Files Found");
                        } else {
                             System.out.println("XML and XSLT Files NOT Found");
                             System.out.println(f1.getPath());
                             System.out.println(f1.getName());
                             xmlfile = "test.xml";
                             xsltfile = "test.xslt";
              InputStream fileXML = getServletContext().getResourceAsStream("WEB-INF/displayfiles/" + xmlfile);
              InputStream fileXSLT = getServletContext().getResourceAsStream("WEB-INF/displayfiles/" + xsltfile);
              OutputStream os = res.getOutputStream();
              TransformerFactory xFactory = TransformerFactory.newInstance();
              StreamSource stylesheet = new StreamSource(fileXSLT);
              Transformer xformer = null;
              try {
              xformer = xFactory.newTransformer(stylesheet);
              } catch (TransformerConfigurationException tfce) {
              tfce.printStackTrace();
              StreamSource input = new StreamSource(fileXML);
              StreamResult output = null;
              try {
              output = new StreamResult(os);
              } catch (Exception e) {
              e.printStackTrace();
              try {
              xformer.transform(input, output);
              } catch (TransformerException xfe) {
              xfe.printStackTrace();
              <pre></pre><pre></pre>

  • How to read a xml file in ActionScript

    In mxml we can find <mx:Model> to load a xml and using
    it easily. But in ActionScript, there is no such a Class about this
    function(only implemented in mxml), so how to load a xml file in a
    easy way in ActionScript?
    And I tried using HTTPService, but I think that is not the
    best solution because the code do not know when the hander get the
    data in xml then the function return that value.
    So please someone give a easy way as <mx:model> in mxml
    to read the xml file?
    Thank you very much.

    Flex is asynchronous so HTTPService with result event handler
    is the way to go.

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

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

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

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

  • How to read an xml file in OSB using file protocol where reading file path is dynamic.

    HI,
    We have to read a xml file from a location and write into Db.
    Here reading file location is dynamic .
    Please suggest

    Hi
    With open dataset you can open any file on the application server. So it should be working, but maybe you are looking for:
    CALL TRANSFORMATION my_transformation
           SOURCE  XML xml_string
           RESULT  ROOT1 = field1
                   ROOT2 = field2.
    Best regards,
    Guido Koopmann

  • How to read an xml file on the server?

    Hi all,
    we need to read an XML file which will be on the appplication server (visible using the transaction AL11).
    We will use the transaction CG3Z in order to upload the file to the server.
    When we try to open it using the instruction OPEN DATASET we have a dump. Which way must we use to open an xml file in this case?
    Thanks for your help.
    David

    Hi
    With open dataset you can open any file on the application server. So it should be working, but maybe you are looking for:
    CALL TRANSFORMATION my_transformation
           SOURCE  XML xml_string
           RESULT  ROOT1 = field1
                   ROOT2 = field2.
    Best regards,
    Guido Koopmann

  • How Can I dispaly XML file with CSS?

    hi,all
    There is maybe a simple way to dispaly a XML file with a CSS file in program.But I don't know.Who can tell me?
    Thank you very much!

    Hi,
    XML documents don't have the link or style elements that are used in HTML to connect style information to particular documents. Instead, the W3C has defined a processing instruction that provides that information, based on the model of the HTML link element. To connect a CSS style sheet to your XML document so that the browser can find it, use a processing instruction like
    <?xml-stylesheet type="text/css" href="URI"?>
    where URI is the address of the style sheet. We'll use a style sheet called display1.css for our first test document. The processing instruction can go right after the XML declaration.
    <?xml version="1.0" ?>
    <?xml-stylesheet type="text/css" href="display1.css"?>
    <test>
    Hope this may help you.
    Regards,
    Anil.
    Technical Support Engineer.

  • How to merge two XML's with JDOM?

    How to merge two xmls's using jdom? like:
    is there a way to add the complete content one xml into the parent node of another xml?
    //in.xml
    <?xml version="1.0"?>
    <people>
    <person>
      <name>ABC</name>
      <email>[email protected]</email>
    </person>
    </people>
    //out.xml
    <?xml version="1.0"?>
    <address>
    <city> abccounty</city>
    <state> abcstate</state>
    </address>
    Merged XML:
    <?xml version="1.0"?>
    <people>
    <person>
      <name>xyz</name>
      <email>[email protected]</email>
    </person>
    <address>
    <city> abccounty</city>
    <state> abcstate</state>
    </address>
    </people>
    import java.util.List;
    import org.jdom.Document;
    import org.jdom.Element;
    import org.jdom.input.SAXBuilder;
    import org.jdom.output.Format;
    import org.jdom.output.XMLOutputter;
    public class MergeXMLS {
         public static void main(String[] args) {
              try{
                  SAXBuilder builder = new SAXBuilder();
                  Document books = builder.build("D:/in.xml");
                  Document onebook = builder.build("D:/out.xml");
                  Element root = books.getRootElement();
                  List rows = root.getChildren();
                  for (int i = 0; i < rows.size(); i++) {
                      Element row = (Element) rows.get(i);
                      onebook.getRootElement().addContent(row.detach());
                      System.out.println(row.getName());
                  new XMLOutputter(Format.getPrettyFormat()).output(onebook, System.out);
              }catch(Exception e){
                   e.printStackTrace();
    }

    The above code only add's the first node.
    I changed the code little differently to
                  SAXBuilder builder = new SAXBuilder();
                  Document books = builder.build("D:/in.xml");
                  Document onebook = builder.build("D:/out.xml");
                 //trying to add second xml into the first
                  books.getRootElement().addContent(onebook.getRootElement().getContent()); 
                  new XMLOutputter(Format.getPrettyFormat()).output(books, System.out);
    here is the exception from the above code:
    org.jdom.IllegalAddException: The Content already has an existing parent "address"
         at org.jdom.ContentList.add(ContentList.java:218)
         at org.jdom.ContentList.add(ContentList.java:140)

  • How to validate the Xml File With Java

    Hi,
    Can pls tell me. I want to validate the XML File for the Some Mandartory TAG. if that if Tag null i want to generate error xml file with error and i want move another folder with java. pls help me as soon as possible

    Use a validating parser (any recent Xerces, for one) and switch on the validation feature. Very much vendor-specific, so look at the docs of your parser. Oh, you do have a schema for these documents, don't you?

  • How to read a XML file from BLOB column and insert in a table - PL/SQL Only

    Hi,
    To make data load more simple to end user instead placing file on the server and use SQL-LOADER, I came up with new idea that using oracle ebusiness suite attachment functionality. that loads a XML file from local PC to a database column(table is fnd_attachments, default data type is BLOB over here).
    I tried with DBMS_LOB and didnt get around.
    Please can anyone tell me how to read the BLOB column using PL/SQL and store the data in a oracle table. Here's the sample XML file and table structure FYI.
    <?xml version="1.0" encoding="UTF-8"?>
    <dataroot xmlns:od="urn:schemas-microsoft-com:officedata" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Corporate_alloc.xsd" generated="2009-07-07T14:17:49">
    <Corporate_alloc>
    <PKG_CODE>BKCORP</PKG_CODE>
    <PKG_NAME>Corporate Edition - Books</PKG_NAME>
    <DET_CODE>B9780080543758</DET_CODE>
    <DET_NAME>Waves, Tides and Shallow-Water Processes</DET_NAME>
    <ALLOCATION_RATIO>0.000041</ALLOCATION_RATIO>
    </Corporate_alloc>
    <Corporate_alloc>
    <PKG_CODE>BKCORP</PKG_CODE>
    <PKG_NAME>Corporate Edition - Books</PKG_NAME>
    <DET_CODE>B9780080534343</DET_CODE>
    <DET_NAME>Hydrostatically Loaded Structures</DET_NAME>
    <ALLOCATION_RATIO>0.000127</ALLOCATION_RATIO>
    </Corporate_alloc>
    </dataroot>
    CREATE TABLE TEST_XML
    ( PKG_CODE VARCHAR2(50),
    PKG_NAME VARCHAR2(100),
    DET_CODE VARCHAR2(20),
    DET_NAME VARCHAR2(500),
    ALLOCATION_RATIO NUMBER )
    Thanks
    EBV

    In regards to #3, use the COLUMNS functionality of XMLTable instead of using Extract. Two simple examples are
    Re: XML Data - Caliculate fields
    Re: Extractvalue function not recognised

Maybe you are looking for

  • Issue material for Subcontracting with reference to PO for multiple batches

    Hi All, Issue: I want to issue 5-6 materials with reference to PO which have multiple batches. How can that be done? Thus, if my raw material in stock are: mat X   Batch 1    50 nos mat X   Batch 2    40 nos mat X   Batch 3     30 nos mat Y Batch 6  

  • BDC problem with F-30

    Hi All, I want to record a BDC for F-30 to clear the deduction line items for a Document. These deduction line items have a "Reason code" with it... When I select a Document Number in F-30, it displays all the line items in a table control.. I need t

  • Why won't my ipad charge properly?

    So I'm trying to figure out something strange with my ipad (ipad 4). Whenever I charge it at home via the regular wall charger its fine and charges away as per normal, however whenever I charge it at uni it just barely charges. On 3 separate occassio

  • Comnpany Code is not fully maintained

    Hi Experts, I am facing an below issue while creating the material master in SAP SD module. ERROR:"Company Code is not fully maintained". However when I checked my assignment by EC01 than it seem no problem. Please resolve it. Thanks in Advance Regar

  • Why Arch Linux official repository provide MariaDB instead of MySQL?

    First, I want to say I'm not an expert in MySQL or any other RDBMS. I just started to learn mysql a month ago. So didn't know exactly what is the practical difference between MariaDB and MySQL. Both are looks the same (except for the prompt as far as