XPathFactory.newInstance().newXPath()

According to the javadoc, a XPath object is not thread safe.
So, the code below is dangerous if this could be invoked from multiple thread?
public String getNodeValue(String xpath, Node document){
          XPath x_path = XPathFactory.newInstance().newXPath();
          String value = null;
          try {
               value = x_path.evaluate(xpath, document);
          } catch (XPathExpressionException e) {
               e.printStackTrace();
          return value;
Is the code below correctly synchronized?
public String getNodeValue(String xpath, Node document){
          XPath x_path = XPathFactory.newInstance().newXPath();
          String value = null;
synchronized (x_path) {
          try {
               value = x_path.evaluate(xpath, document);
          } catch (XPathExpressionException e) {
               e.printStackTrace();
          return value;
     }

Thank you very much for your reply.
Is your XPath variable a class field or is it a method-local variable?It's a method local variable.
If it's a class field, is there a chance that it will be manipulated by different objects at the same time?It's not a class field so I don't think there's any chance.
THerefore, my method is okay and not necessary to be synchronized?
Edited by: Liveinjapan on Sep 30, 2008 7:52 PM

Similar Messages

  • XPathFactory.newInstance() throws NullPointerException

    Even though the javadoc of XPathFactory.newInstance() says:
    Since the implementation for the W3C DOM is always available, this method will never fail.
    I get a NullPointerException when I use my app as an ActiveX Java Bean:
    java.lang.NullPointerException
         at javax.xml.xpath.XPathFactoryFinder._newFactory(Unknown Source)
         at javax.xml.xpath.XPathFactoryFinder.newFactory(Unknown Source)
         at javax.xml.xpath.XPathFactory.newInstance(Unknown Source)
         at javax.xml.xpath.XPathFactory.newInstance(Unknown Source)
         at d.i.x.XMLUtils.getXPathValue(XMLUtils.java:553)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
         at java.lang.reflect.Method.invoke(Unknown Source)
         at d.i.IUtils.call(ICUtils.java:368)
         at d.i.c.JavaWrapper.call(JavaWrapper.java:489)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
         at java.lang.reflect.Method.invoke(Unknown Source)
         at sun.plugin.javascript.invoke.JSInvoke.invoke(Unknown Source)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
         at java.lang.reflect.Method.invoke(Unknown Source)
         at sun.plugin.javascript.JSClassLoader.invoke(Unknown Source)
         at sun.plugin.com.MethodDispatcher.invoke(Unknown Source)
         at sun.plugin.com.DispatchImpl.invokeImpl(Unknown Source)
         at sun.plugin.com.BeanDispatchImpl.invoke(Unknown Source)

    I had to wrap the fix mentioned above in an accessControlled method to get around the security issue that I don't really think should have been triggered by this particular call to get this code to work when called from a JDialog in an applet. It worked fine in an application without either fix. Here's what the resulting code looked like: (Let me know if there's a more elegant solution ;-) And, Thanks for the fix listed above. I don't think I would have figured that out.
    :     public static XPath getXPathFactoryAccessControlled(){
              GetXPathAccessControlledAction aca = new GetXPathAccessControlledAction();
              AccessController.doPrivileged(aca);
              return aca.getValue();
         static class GetXPathAccessControlledAction implements PrivilegedAction<Object> {
              private XPath value;
              public GetXPathAccessControlledAction(){}
    public Object run() {
                   try{
                        ClassLoader cl = Thread.currentThread().getContextClassLoader();
                        Thread.currentThread().setContextClassLoader(new URLClassLoader(new URL[0], cl));
                        value = XPathFactory.newInstance().newXPath();
                        Thread.currentThread().setContextClassLoader(cl);
                   }catch (SecurityException se){
                        System.out.println("Error in Utils.getXPathAccessControlled: " + se.getMessage());
                   } catch (Exception se){
                        System.out.println("Error in Utils.getXPathAccessControlled: " + se.getMessage());
              return value;
              public XPath getValue() {return value;}
         }

  • How get all child elements from XML

    Hi
    I have one xml i tried to parse that xml using dom parser and i need to get some child elements using java
    <Group>
    <NAME>ABC</NAME>
    <Age>24</AgeC>
    ---------some data here......
    <Group1>
    <group1Category>
    <NAME>ABCTest</NAME>
    <age>27</Age>
    ----Some data here
    <group1subcategory>
    <subcategory>
    <NAME>ABCDEF</NAME>
    <age>28</Age>
    my intention was
    get group name (here ABC) i need all other name value from group1category ,group1 subcategory but pblm that
    my xml contains any number of Group nodes...but only i want name contains ABC
    i wriiten code like this
    DocumentBuilderFactory factory = DocumentBuilderFactory
    .newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(xmlFile);
    NodeList nodeList = document.getElementsByTagName("*");
    for (int i = 0; i < nodeList.getLength(); i++)
    Element element = (Element) nodeList.item(i);
    what is next step i need to do..please help

    964749 wrote:
    Sorry for inconvenience caused..i only asked if any ideas i not ask any body to spent time for me...
    This is simple code developed using xpath..i not know how i proceed further
    public class Demo {
    public static void main(String[] args) {
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    try {
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document dDoc = builder.parse("hello.xml");
    XPath xpath = XPathFactory.newInstance().newXPath();
    javax.xml.xpath.XPathExpression expr = xpath.compile("//Group/NAME");
    Object Name= expr.evaluate(dDoc, XPathConstants.STRING);
    System.out.println(Name);
    } catch (Exception e) {
    e.printStackTrace();
    i need get group name (here ABC) i need all other name value from group1category ,group1 subcategory but pblm that
    ..how i done in XPATH and also do manipulation of remining result...
    i also try with DOM like
    NodeList nodeList = document.getElementsByTagName("GROUP");
    for (int i = 0; i < nodeList.getLength(); i++)
    Element element = (Element) nodeList.item(i);
    if (element.getNodeName().matches("ECUC-MODULE-DEF"))
    String str=((Element) nodeList.item(i)).getElementsByTagName("NAME").item(0).getFirstChild().getNodeValue();
    if(str.equalsIgnoreCase("abc")){
    NodeList children = element.getChildNodes();
    for (int k = 0; k < children.getLength(); k++) {
    Node child = children.item(k);
    System.out.println("children"+children.getLength());
    if (child.getNodeType() != Node.TEXT_NODE) {
    if(child.getNodeName().equalsIgnoreCase("Group1"))
    how iterate for particular ABC name to group1 and subcategoryFew things
    1. Use code tags to format code
    2. Explain the problem statement clearly. Take time to formulate your question. Explain what you expect from your code and what you are getting along with any exceptions that are being thrown

  • XML invalid character -  a single quote problem

    Hi, I am reading in an xml file, then write the file to output. The problem is that the input file has a strange single quote character [ *�*  ] - lets call it single quoate A, which is different from [  *'*  ] , that is the key next to the [ ; ] key on an English keyboard - lets call it single quate B. And in fact there isnt a key to input single quote A, I guess the appearance of single quote A is due to encoding.
    If I open the input xml file in browser, it works ok and displays the single quote A.
    Once I read in the xml file into memory, by debugging I can still see that single quote A is corrected encoded;
    However once I rewrite the same content to output, the single quote A character is changed, and if i open the file in browser, it says 'invalid character' because single quote A were changed when written to output and cannot be rendered.
    Both input and output xml are using UTF-8 encoding. How can I solve this problem please?
    The xml file looks:
    <?xml version="1.0" encoding="UTF-8" ?>
    <content>....1980�s (Peacock and Williams, 1986; Keay, 1984)</content> My code for reading
    String _xquery ="//content/text()";
    Document _xmlDoc= DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("myxml.xml");
    XPath _xpath = XPathFactory.newInstance().newXPath();
    NodeList nodes = (NodeList) _xpath.compile(query).evaluate(_xmlDoc, XPathConstants.NODESET);
    List<String> res = new ArrayList<String>(nodes.getLength());
    for (int i = 0; i < nodes.getLength(); i++) {
        res.add(nodes.item(i).getNodeValue());
    String valueToOuput=res.toString() //this is the value to be output to xml, it shoud look like "[....1980�s (Peacock and Williams, 1986; Keay, 1984)]"my code for writing xml
    Element root=new Element("root");;
    Element content= new Element("output-content")
    content.setText(valueToOutput);
    root.addContent(content);
    PrintWriter writer = new PrintWriter(new FileWriter(f));
    new XMLOutputter().output(domDocument, writer);
    writer.close();

    Hi, sorry I have fixed the problem... instead of using PrintWriter, I used Fileoutputstream, and it solved the problem. Thanks!

  • How to retrieveText Node value

    I am generating an xml doc containing two set of data (one from ord table corresponding to orderId passed to the stored proc from calling app) and then appending child nodes for the values coming as In parameter. When I try to get the value of text node of the child element which has been appended through code, I am getting no values (I could only get to the first child value by (<xsl:value-of select="/EQUITYCONNECT//text()"/>). If I have to get the values of ORD_ID,EXECSIDE and SECURITY node in /EQUITYCONNECT/EXECRPT, how will the XPATH expression coded. (<xsl:value-of select="/EQUITYCONNECT/EXECRPT/EXECSIDE/text()"/> returns null value.
    Here is the code segment
    PROCEDURE xmlRules(orderID NUMBER,execSide NUMBER,security VARCHAR2) IS
    p xmlparser.Parser;
    xmldoc xmldom.DOMDocument;
    docnode xmldom.DOMNode;
    newele xmldom.DOMElement;
    newele1 xmldom.DOMElement;
    newelenode xmldom.DOMNode;
    newelenode1 xmldom.DOMNode;
    textele xmldom.DOMText;
    newtextelenode xmldom.DOMNode;
    compnode xmldom.DOMNode;
    nl xmldom.DOMNodeList;
    n xmldom.DOMNode;
    len number;
    rootnode xmldom.DOMNode;
    vbuffer varchar2(32767);
    line varchar2(4000);
    ordQueryCtx DBMS_XMLGen.ctxHandle;
    execRpt CLOB;
    result CLOB;
    result1 CLOB;
    xmlout VARCHAR2(4000);
    strResult VARCHAR2(4000);
    strResult1 VARCHAR2(4000);
    prtOut VARCHAR2(255);
    begin
    -- new parser
    p := xmlparser.newParser;
    -- set some characteristics
    xmlparser.setValidationMode(p, FALSE);
    -- xmlparser.setErrorLog(p, dir || '/' || errfile);
    xmlparser.setPreserveWhiteSpace(p, TRUE);
    -- set up the query context...!
    ordQueryCtx := DBMS_XMLGen.newContext('select * from ord where ord_id ='|| orderID);
    dbms_xmlgen.setrowsettag(ordQueryCtx,'EQUITYCONNECT');
    dbms_xmlgen.setrowtag(ordQueryCtx,'ORDER');
    -- get the result..!
    result := DBMS_XMLGen.getXML(ordQueryCtx);
    -- Turn into string (test purposes only)
    strResult := dbms_lob.SUBSTR(result);
    -- parse xml file
    xmlparser.parseclob(p,result);
    -- get document
    xmldoc := xmlparser.getDocument(p);
    -- get all elements of document
    nl := xmldom.getElementsByTagName(xmldoc, '*');
    len := xmldom.getLength(nl);
    -- check if number of element nodes are atleast 2
    if len > 1 then
    dbms_output.put_line('Document has more than two elements including Root');
    -- get root element of document
    rootnode := xmldom.item(nl,0);
    -- get the element next to the root element
    n := xmldom.item(nl, 1);
    -- make node for dom document
    docnode := xmldom.makeNode(xmldoc);
    -- create a new element node
    newele := xmldom.createElement(xmldoc, 'EXECRPT');
    newelenode := xmldom.makeNode(newele);
    newele1 := xmldom.createElement(xmldoc, 'ORD_ID');
    newelenode1 := xmldom.makeNode(newele1);
    compnode := xmldom.appendChild(newelenode, newelenode1);
    -- create a new text node
    textele := xmldom.createTextNode(xmldoc, orderID);
    newtextelenode := xmldom.makeNode(textele);
    -- append text node to element node
    compnode := xmldom.appendChild(newelenode1, newtextelenode);
    newele1 := xmldom.createElement(xmldoc, 'EXECSIDE');
    newelenode1 := xmldom.makeNode(newele1);
    compnode := xmldom.appendChild(newelenode, newelenode1);
    -- create a new text node
    textele := xmldom.createTextNode(xmldoc, execSide);
    newtextelenode := xmldom.makeNode(textele);
    -- append text node to element node
    compnode := xmldom.appendChild(newelenode1, newtextelenode);
    newele1 := xmldom.createElement(xmldoc, 'SECURITY');
    newelenode1 := xmldom.makeNode(newele1);
    compnode := xmldom.appendChild(newelenode, newelenode1);
    -- create a new text node
    textele := xmldom.createTextNode(xmldoc, security);
    newtextelenode := xmldom.makeNode(textele);
    -- append text node to element node
    compnode := xmldom.appendChild(newelenode1, newtextelenode);
    -- insert the node just after the parent node
    newelenode := xmldom.insertBefore(rootnode, newelenode, n);
    -- Perform these two operations to avoid ORA-20000 (cannot write to NULL CLOB)
    dbms_lob.createtemporary(result1, true, dbms_lob.session);
    dbms_lob.open(result1, dbms_lob.lob_readwrite);
    xmldom.writetoclob(docnode,result1);
    strResult1 := dbms_lob.substr(result1);
    xmldom.writeToBuffer(docnode, vbuffer);
    -- print the output stored in buffer
    loop
    exit when vbuffer is null;
    line := substr(vbuffer,1,instr(vbuffer,chr(10))-1);
    dbms_output.put_line('| '||line);
    vbuffer := substr(vbuffer,instr(vbuffer,chr(10))+1);
    end loop;
    -- Call Java function which takes (varchar2, varchar2) as args
    xmlout := transform_xml(strResult1, '<html xsl:version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    lang="en">
    <head>
         <title>Order Report</title>
    </head>
    <body>
         <table border="1">
         <tr>
              <th>Row Number</th>
              <th>Order ID</th>
              <th>Order ID</th>
              <th>Txn</th>
              <th>Security</th>
              <th>Quantity</th>
         </tr>
         <xsl:for-each select="EQUITYCONNECT">
              <!-- order the result by revenue -->
              <xsl:sort select="ORD_ID"
                   data-type="number"
                   order="ascending"/>
              <tr>
              <td>
                   <xsl:value-of select="ORDER/ORD_ID"/>
              </td>
              <td>
    <xsl:value-of select="/EQUITYCONNECT//text()"/>          </td>
         </tr>
         </xsl:for-each>
         </table>
    </body>
    </html>');
    -- Close the query context
    DBMS_XMLGen.closeContext(ordQueryCtx);
    end if;
    exception
    when xmldom.INDEX_SIZE_ERR then
    raise_application_error(-20120, 'Index Size error');
    when xmldom.DOMSTRING_SIZE_ERR then
    raise_application_error(-20120, 'String Size error');
    when xmldom.HIERARCHY_REQUEST_ERR then
    raise_application_error(-20120, 'Hierarchy request error');
    when xmldom.WRONG_DOCUMENT_ERR then
    raise_application_error(-20120, 'Wrong doc error');
    when xmldom.INVALID_CHARACTER_ERR then
    raise_application_error(-20120, 'Invalid Char error');
    when xmldom.NO_DATA_ALLOWED_ERR then
    raise_application_error(-20120, 'Nod data allowed error');
    when xmldom.NO_MODIFICATION_ALLOWED_ERR then
    raise_application_error(-20120, 'No mod allowed error');
    when xmldom.NOT_FOUND_ERR then
    raise_application_error(-20120, 'Not found error');
    when xmldom.NOT_SUPPORTED_ERR then
    raise_application_error(-20120, 'Not supported error');
    when xmldom.INUSE_ATTRIBUTE_ERR then
    raise_application_error(-20120, 'In use attr error');
    when others then
    dbms_output.put_line('exception occured' || sqlcode || substr(sqlerrm, 1, 100));
    end xmlRules;
    function xml_transform is taking the xml and xsl file as string and returning me xml as string after processing. Basiccally I have to do some comparison on the value of /EQUITYCONNECT/ORDER elements and /EQUITYCONNECT/EXECRPT element.
    Any help will be appreciated.

    Here you go:
           Node nameNode =
                    (Node) XPathFactory.newInstance().newXPath().evaluate(
                            "/root/name", doc, XPathConstants.NODE);
            nameNode.setTextContent("bob");

  • Problems by getting info out of XML file with a HTTP request

    Hi,
    I have a litte question. I'm working on an application that works together with google maps. In my java code, I get general information about address out of one database table, and I want to add some geographic information like coordinates that I want to retrieve from Google Maps through HTTP:
    Right now my code is like:
    while (resultSet.next())
                             title = resultSet.getString("title").replaceAll("'","''").toUpperCase();
                             author = resultSet.getString("author").replaceAll("'","''").toUpperCase();
                             location = resultSet.getString("location").replaceAll("'","''").toUpperCase();
                             straatnaam = resultSet.getString("straatnaam").replaceAll("'","''").toUpperCase();
                             nummer = resultSet.getString("nummer");
                             landcode = resultSet.getString("landcode").replaceAll("'","''").toUpperCase();
                             address = straatnaam + " " + nummer + " , " + location + " " + landcode;
                             url = "http://maps.google.com/maps/geo?q=" + address + "&output=xml&key=+key+";
                             String query = "INSERT INTO data2 VALUES ('" + i + "','" + title + "','" + author + "','" + resultSet.getString("date1") + "','" + resultSet.getString("date2") + "','" + location + "','" + resultSet.getString("postcode") + "','" + straatnaam + "','" + resultSet.getString("nummer") + "','" + landcode + "','+something like url.getCoordX+','something like url.getCoordY')";
                             success = sql2.executeUpdate(query);
                             i++;
    Now I don't know how I can handle that. Is it possible to do an HTTP request in Java without using Java Script of servlets? I just want to get the X and Y coordinates out of the XML file.
    The XML file will be something like:
    <kml xmlns="http://earth.google.com/kml/2.0">
    <Response>
    <name>1600 amphitheatre mountain view ca</name>
    <Status>
    <code>200</code>
    <request>geocode</request>
    </Status>
    <Placemark>
    <address>
    1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA
    </address>
    <AddressDetails Accuracy="8">
    <Country>
    <CountryNameCode>US</CountryNameCode>
    <AdministrativeArea>
    <AdministrativeAreaName>CA</AdministrativeAreaName>
    <SubAdministrativeArea>
    <SubAdministrativeAreaName>Santa Clara</SubAdministrativeAreaName>
    <Locality>
    <LocalityName>Mountain View</LocalityName>
    <Thoroughfare>
    <ThoroughfareName>1600 Amphitheatre Pkwy</ThoroughfareName>
    </Thoroughfare>
    <PostalCode>
    <PostalCodeNumber>94043</PostalCodeNumber>
    </PostalCode>
    </Locality>
    </SubAdministrativeArea>
    </AdministrativeArea>
    </Country>
    </AddressDetails>
    <Point>
    <coordinates>-122.083739,37.423021,0</coordinates>
    </Point>
    </Placemark>
    </Response>
    </kml>
    many greetings and thanks in advance
    Mathias

    Hi, sorry for being not so clear. My question was actually if it is possible to do a HTTP request in Java without using servlets or being in Java Script. Actually my question was more specific for Google maps, because it didn't seem to work. It was my mistake, and already solved, to forget to make the webservice-call "URL-encoded". Because of that, I always received a HTTP 400 error, and that's why I thought it wouldn't be possible.
    But now I have another, perhaps for you guys stupid question. The result I get from the webservice URL is of the form:
    <?xml version="1.0" encoding="UTF-8"?>
    <kml xmlns="http://earth.google.com/kml/2.0">
    <Response>
         <name>nieuwelaan 38, Hamme</name>
         <Status>
              <code>200</code>
              <request>geocode</request>
         </Status>
         <Placemark id="p1">
              <address>Nieuwelaan 38, 9220 Hamme, Hamme, Belgium</address>
              <AddressDetails Accuracy="8" xmlns="urn:oasis:names:tc:ciq:xsdschema:xAL:2.0">
              <Country>
                   <CountryNameCode>BE</CountryNameCode>
                   <AdministrativeArea>
                        <AdministrativeAreaName>Vlaams Gewest</AdministrativeAreaName>
                        <SubAdministrativeArea>
                             <SubAdministrativeAreaName>Oost-Vlaanderen</SubAdministrativeAreaName>
                             <Locality>
                                  <LocalityName>Hamme</LocalityName>
                                  <DependentLocality>
                                       <DependentLocalityName>Hamme</DependentLocalityName>
                                       <Thoroughfare>
                                            <ThoroughfareName>Nieuwelaan 38</ThoroughfareName>
                                       </Thoroughfare>
                                       <PostalCode>
                                            <PostalCodeNumber>9220</PostalCodeNumber>
                                      </PostalCode>
                                 </DependentLocality>
                            </Locality>
                        </SubAdministrativeArea>
                   </AdministrativeArea>
             </Country>
             </AddressDetails>
             <Point>
                   <coordinates>4.126295,51.097724,0</coordinates>
             </Point>
         </Placemark>
    </Response>
    </kml> Now I want to get the value of the coordinates field.
    This is my code:
    address = URLEncoder.encode(address, "UTF-8");
    urlString = "http://maps.google.com/maps/geo?q=" + address + "&output=xml&key=ABQIAAAA9fEXNK-q6vKpPU0JCmPPkxQjbVBpjtblJJYkDfbMo0e51afwehRmujfvBtJqx1Qehg6e6QgCRY8poA";
    url = new URL(urlString);
    XPath xPath = XPathFactory.newInstance().newXPath();
    Document domDoc = processData(url);
    path = "/kml/Response/Placemark/Point/coordinates";
    coord = xPath.evaluate(path, domDoc);
    System.out.println("coord : " + coord);Now, in the last line, by writing out the value of coord to my screen, I get the value "1", instead of "4.126295,51.097724,0" I would expect, anyone knows what I'm doing wrong?
    greetings
    Mathias

  • String to XML

    Hi everyone,
    i'm just writing a method, that gets a string and a XPath and want writes the string to the specific XPath in my xml document. The problem ist, that the string itself can contain nodes like (e.g. <image> or something else from my dtd, so i got some problems converting the string to xml. Actually i'm trying this:
         public static void setEditFragment(String content, String xPath) throws Exception {
             DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
             DocumentBuilder builder  = factory.newDocumentBuilder();
             Document document = builder.parse("data.xml");
             XPath xpath = XPathFactory.newInstance().newXPath();
             Node node = (Node)xpath.evaluate(xPath, document, XPathConstants.NODE);
             System.out.println(content);
             node.setTextContent(content);
             // Use a XSLT transformer for writing the new XML file
                Transformer transformer = TransformerFactory.newInstance().newTransformer();
                // Set output to IsoLatin1
                transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
             DOMSource        source = new DOMSource( document );
             FileOutputStream os     = new FileOutputStream("tmp.xml");
             StreamResult     result = new StreamResult( os );
             transformer.transform( source, result ); 
         }but of course this will not work and sets up some cryptic signs in mein xml document....
    can anyone give me advice ?
    Thanks !

    Well, if you already have the data XML encoded, then just write them to a file:
    http://java.sun.com/docs/books/tutorial/essential/io/index.html
    Make sure you encode the data with UTF8:
    http://java.sun.com/javase/6/docs/api/java/lang/String.html#getBytes(java.lang.String)
    Write "<?xml version="1.0" encoding="utf-8"?>" before the data!
    Note however, I generally don't recommend to write XML data by hand. Rather use a framework like JAXB.
    -Puce
    Edited by: Puce on May 8, 2008 1:36 PM

  • Problem in xpath reading

    hi to all,
    Iam using javax.xml.xpath.XPath to parse and read the xml file. It is working fine in java 1.5 version. but i want the same requirement in java 1.4. When iam using same code in java 1.4 it is throwing exceptions. Iam giving the code....
    First of all iam creating XPathReader class for xpath parsing and reading.
    import java.io.IOException;
    import javax.xml.XMLConstants;
    import javax.xml.namespace.QName;
    import javax.xml.parsers.*;
    import javax.xml.xpath.*;
    import org.w3c.dom.Document;
    import org.xml.sax.SAXException;
    public class XPathReader {
    private DocumentBuilder documentBuilder=null;
    private Document xmlDocument;
    private XPath xPath;
    public XPathReader() {
    initObjects();
    private void initObjects(){
    try {
    documentBuilder= DocumentBuilderFactory.
    newInstance().newDocumentBuilder();
    xPath = XPathFactory.newInstance().
    newXPath();
    }catch (Exception ex) {
    ex.printStackTrace();
    public void parse(String filename){
    try {
    xmlDocument=documentBuilder.parse(filename);
    } catch (Exception e) {
    e.printStackTrace();
    public Object read(String expression,
    QName returnType){
    try {
    XPathExpression xPathExpression =
    xPath.compile(expression);
    return xPathExpression.evaluate
    (xmlDocument, returnType);
    } catch (XPathExpressionException ex) {
    ex.printStackTrace();
    return null;
    In another class iam just creating object of XPathReader
    XPathReader reader= new XPathReader();
    reader.parse(....xml file path that which u want to parse......);
    String expression = ....
    NodeList rootNode = (NodeList)reader.read(expression,XPathConstants.NODESET);
    here generally i will get NodeList object...
    this code works fine in java 1.5
    but it is showing exceptions in 1.4 as...
    java.lang.RuntimeException: XPathFactory#newInstance() failed to create an XPathFactory for the default object model: http://java.sun.com/jaxp/xpath/dom with the XPathFactoryConfigurationException: javax.xml.xpath.XPathFactoryConfigurationException: No XPathFctory implementation found for the object model: http://java.sun.com/jaxp/xpath/dom
    at javax.xml.xpath.XPathFactory.newInstance(Unknown Source)
    I think XPathFactory is not in the 1.4. So, is there any alternative to overcome the above problem?
    if any buddy knows please help me...
    thanks to one and all...
    Edited by: [email protected] on May 7, 2008 4:36 AM

    You need to post the code so we can help

  • Using xpath.evaluate(): xpath exp with multiple namespaces

    Hi,
    I have to evaluate a xpath expression with parent node and child node having different namespaces. Like : env:parent/mig:child.
    I have set the namespacecontext for the child node[i.e., for the prefix 'mig'.]
    But am getting this error :
    javax.xml.transform.TransformerException: Prefix must resolve to a namespace: env
    How can I set the namespace context for both the parent and child nodes? Or is there are any other way of doing it?
    I cant use //mig:child as the requirement needs the whole xpath expression [env:parent/mig:child] to be given as input for the xpath.evaluate() method.
    Here's the code :
    File file = new File("D:\\Backup\\XMLs\\test.xml");
    Document xmlDocument = builder.parse(file);
    XPath xpathEvaluator = XPathFactory.newInstance().newXPath();
    xpathEvaluator.setNamespaceContext(new NamespaceContextProvider("env", "http://xmlns.oracle.com/apps/account/1.0"));
    NodeList nodeList =
    (NodeList)xpathEvaluator.evaluate("/env:parent/mig:child", xmlDocument,
    XPathConstants.NODESET);
    xpathEvaluator.setNamespaceContext(new NamespaceContextProvider("mig", "http://xmlns.oracle.com/apps/account/1.0"));
    Thanks in advance.

    If you want, I can help you tomorrow. Call me at my nieuwegein office or mail me at marco[dot]gralike[at]amis[dot]nl
    I have some time tomorrow, so I can help you with this. My next presentation for UKOUG will be on XML indexes strategies anyway...
    In the meantime and/or also have a look at:
    XML Howto's (http://www.liberidu.com/blog/?page_id=441) specifically:
    XML Indexing
    * Unstructured XMLIndex (part 1) – The Concepts (http://www.liberidu.com/blog/?p=228)
    * Unstructured XMLIndex (Part 2) – XMLIndex Path Subsetting (http://www.liberidu.com/blog/?p=242)
    * Unstructured XMLIndex (Part 3) – XMLIndex Syntax Dissected (http://www.liberidu.com/blog/?p=259)
    * Unstructured XMLIndex Performance and Fuzzy XPath Searches (http://www.liberidu.com/blog/?p=310)
    * Structured XMLIndex (Part 1) – Rules of Numb (http://www.liberidu.com/blog/?p=1791)
    * Structured XMLIndex (Part 2) – Howto build a structured XMLIndex (http://www.liberidu.com/blog/?p=1798)
    * Structured XMLIndex (Part 3) – Building Multiple XMLIndex Structures (http://www.liberidu.com/blog/?p=1805)
    The posts were based on Index for XML with Repeated Elements maybe that is a bit better to read than on my notepad on the internet (aka blog)
    Edited by: Marco Gralike on Oct 28, 2010 7:51 PM

  • Using XPath to create nodes

    Hi,
    Obviously the main use of XPath is to query the state of an XML document... the equivalent to a "select" statement in SQL.
    DOM4J has methods that allow you to use XPath as the equivalent to "insert" statements in SQL. You can specify an XPath like "/Hello/World/Value = 3" and apply this XPath to an XML document so that it creates something like this for you:
    <Hello>
    <World>
    <Value>3</Value>
    </World>
    </Hello>
    This is actually very useful for an investment banking application that I'm working on.
    The problem with DOM4J is that it doesn't handle attributes or conditionals well. If you specify
    /Hello[@name=2]/World = 3
    I would expect
    <Hello name=2>
    <World>3</World>
    </Hello>
    to be produced. Instead, it produces
    <Hello[@name=2]>
    <World>3</World>
    </Hello>
    These are all simple examples. What I'm doing in real life is using XPath to insert nodes into a complicated XML document that already has a lot of structure. I'm only adding one or two elements to big documents.
    Is there anything at all like this available in the JDK 1.5 release. I've had a good look, and XPath looks like it's only for queries. Is this correct?

    I think this might do what you need...
    // Create a dummy XML document
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputStream bais = new ByteArrayInputStream("<test><e1/></test>".getBytes());       
    Document doc = db.parse(bais);
    // Define the XPath expression to "select" the parent element in the document       
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression xpathExpression = xpath.compile("/test/e1");    
    // Select the parent node (should probably chuck an ex if not present)       
    Node node = (Node) xpathExpression.evaluate(doc, XPathConstants.NODE);
    // Create and append the child element
    node.appendChild(doc.createElement("newElement"));
    // Convert the Document into a string
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(baos);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.transform(source, result);
    // <?xml version="1.0" encoding="UTF-8"?><test><e1><newElement/></e1></test>
    System.out.println(baos.toString());

  • Creating a node in an XML Document

    Hi!
    i need to insert a new element in an existing xml document. for example,
    <bookinfo>
    <book>
    <bookname>A</bookname>
    <author>B</author>
    </book>
    <book>
    <bookname>C</bookname>
    <author>D</author>
    </book>
    </bookinfo>
    In this document if i want to insert another element using Xpath, say,<publisher> in <book> node, how to insert it.
    I'm using DOM parser for parsing the xml file.
    Any help to solve this issue appreciated.
    Thanks in advance.

    final class Foo {
        private static final String MARKUP =
            "<bookinfo>\n" +
              "<book isbn='1234'>\n" +
              "<bookname>A</bookname>\n" +
              "<author>B</author>\n" +
              "</book>\n" +
              "<book isbn='5678'>\n" +
              "<bookname>C</bookname>\n" +
              "<author>D</author>\n" +
              "</book>\n" +
              "</bookinfo>";
        private Foo() {
            super();
        public static final void main(final String[] args)
            throws XPathExpressionException {
            String isbn = args.length > 0 ? args[0] : "1234";
            String publisher = args.length > 1 ? args[1] : "Sample Publisher";
            Document document = ...  // Initialize somehow
            XPath xpath = XPathFactory.newInstance().newXPath();
            String expression = "//bookinfo/book[@isbn=" + isbn + "]";
            Element book = (Element) xpath.evaluate(expression, document.getDocumentElement(), XPathConstants.NODE);
            if (book == null) {
                throw new RuntimeException("Unable to find ISBN " + isbn);
            Element newPublisher = document.createElement("publisher");
            newPublisher.setAttribute("name", publisher);
            book.appendChild(newPublisher);
    }- Saish

  • Can't Parse XHTML with XPATH

    I can't seem to parse a simple XHTML 1.1 document with XPATH. In the code below, the string xmlDoesntWork is taken directly from http://www.w3.org/TR/2001/REC-xhtml11-20010531/conformance.html. However, XPATH can't find the <title> element unless I remove the DOCTYPE line & the xmlns attribute from the <html> element (the xmlWorks string). XPATH returns null for the <title> element in the first string, but correctly retrieves the title in the second string. I tried adding a namespace context argument, but that didn't make any difference.
    Can anyone see what I'm doing wrong?
    import java.io.StringReader;
    import javax.xml.namespace.NamespaceContext;
    import javax.xml.xpath.XPath;
    import javax.xml.xpath.XPathConstants;
    import javax.xml.xpath.XPathExpression;
    import javax.xml.xpath.XPathFactory;
    import org.w3c.dom.Node;
    import org.xml.sax.InputSource;
    public class Test
    public static void main(String[] unused)throws Exception
       final String path = "/html/head/title";
       final String xmlDoesntWork =
          "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
          "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">" +
          "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" >" +
          "<head>" +
          "<title>Virtual Library</title>" +
          "</head>" +
          "<body>" +
          "<p>Moved to <a href=\"http://vlib.org/\">vlib.org</a>.</p>" +
          "</body>" +
          "</html>";
       String title = getText(xmlDoesntWork, path, null);
       System.out.println("Title: " + title);  
       final String xmlWorks =
          "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
          "<html>" +
          "<head>" +
          "<title>Virtual Library</title>" +
          "</head>" +
          "<body>" +
          "<p>Moved to <a href=\"http://vlib.org/\">vlib.org</a>.</p>" +
          "</body>" +
          "</html>";
       title = getText(xmlWorks, path, null);
       System.out.println("Title: " + title);  
    private static String getText(String xml, String path, NamespaceContext context)
       throws Exception
       StringReader reader = new StringReader(xml);          // Get input source
       InputSource  source = new InputSource(reader);
       XPath xpath = XPathFactory.newInstance().newXPath();
       if (context != null)                                  // If there's a namespace context
          xpath.setNamespaceContext(context);                // Inform XPATH
       XPathExpression expression = xpath.compile(path);     
       Node node = (Node)expression.evaluate(source, XPathConstants.NODE);
       return node == null ? null : node.getTextContent();
    }

    I'm perplexed. I made the change you suggested (code below), and still get the same error. Did I miss something?
    import java.io.StringReader;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Iterator;
    import javax.xml.namespace.NamespaceContext;
    import javax.xml.xpath.XPath;
    import javax.xml.xpath.XPathConstants;
    import javax.xml.xpath.XPathExpression;
    import javax.xml.xpath.XPathFactory;
    import org.w3c.dom.Node;
    import org.xml.sax.InputSource;
    public class Test implements NamespaceContext
    private static final HashMap<String,String> URI_MAP    ;
    private static final HashMap<String,String> PREFIX_MAP ;
    private static final String XHTML_PREFIX = "xhtml"                                     ;
    private static final String XHTML_URI    = "http://www.w3.org/1999/xhtml"              ;
    private static final String XSI_PREFIX   = "xsi"                                       ;
    private static final String XSI_URI      = "http://www.w3.org/2001/XMLSchema-instance" ;
    static
       URI_MAP = new HashMap<String,String>();
       URI_MAP.put(XSI_PREFIX  , XSI_URI  );
       URI_MAP.put(XHTML_PREFIX, XHTML_URI);
       PREFIX_MAP = new HashMap<String,String>();
       PREFIX_MAP.put(XSI_URI  , XSI_PREFIX  );
       PREFIX_MAP.put(XHTML_URI, XHTML_PREFIX);
    public static void main(String[] unused)throws Exception
       new Test().run();
    public void run()throws Exception
       final String path = "/xhtml:html/xhtml:head/xhtml:title";
       final String xmlDoesntWork =
          "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
          "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">" +
          "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" >" +
          "<head>" +
          "<title>Virtual Library</title>" +
          "</head>" +
          "<body>" +
          "<p>Moved to <a href=\"http://vlib.org/\">vlib.org</a>.</p>" +
          "</body>" +
          "</html>";
       String title = getText(xmlDoesntWork, path, this);
       System.out.println("Title: " + title);  
       final String xmlWorks =
          "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
          "<html>" +
          "<head>" +
          "<title>Virtual Library</title>" +
          "</head>" +
          "<body>" +
          "<p>Moved to <a href=\"http://vlib.org/\">vlib.org</a>.</p>" +
          "</body>" +
          "</html>";
       title = getText(xmlWorks, path, this);
       System.out.println("Title: " + title);  
    private static String getText(String xml, String path, NamespaceContext context)
       throws Exception
       StringReader reader = new StringReader(xml);          // Get input source
       InputSource  source = new InputSource(reader);
       XPath xpath = XPathFactory.newInstance().newXPath();
       if (context != null)                                  // If there's a namespace context
          xpath.setNamespaceContext(context);                // Inform XPATH
       XPathExpression expression = xpath.compile(path);     
       Node node = (Node)expression.evaluate(source, XPathConstants.NODE);
       return node == null ? null : node.getTextContent();
    * Determines the URI associated with a namespace prefix.
    * @param prefix The prefix.
    * @return The  URI.
    public String getNamespaceURI(String prefix)
       String URI = URI_MAP.get(prefix);
       return URI;
    * Determines the prefix associated with a namespace URI.
    * @param URI The URI.
    * @return The prefix.
    public String getPrefix(String URI)
       String prefix = PREFIX_MAP.get(URI);
       return prefix;
    * Retrieves prefixes associated with a namespace URI.
    * @param URI The URI.
    * @return An iterator to the collection of prefixes.
    public Iterator getPrefixes(String URI)
       ArrayList<String> list = new ArrayList<String>();
       list.add(getPrefix(URI));
       return list.iterator();
    }

  • NamespaceContext.getPrefix() never called

    I am a newbie in the Java XML world.
    Here is my issue and the snippet of code is used to explain the problem:
    XPathVariableResolver jxvr = new JSTLXPathVariableResolver(pageContext);
    Node contextNode = adaptParamsForXalan(n, xpathString.trim(), jxvr);
    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(jstlXPathNamespaceContext); //jstlXPathNamespaceContext is
    // initialized somewhere else
    xpath.setXPathVariableResolver(jxvr);
    Now when the xpath is evaluated using:
    xpath.evaluate(xpathString, contextNode);
    Under the debugger I can see that this call eventually calls the getNamespaceURI() method
    of JSTLXPathNamespaceContext (class for jstlXPathNamespaceContext) and then after that
    I land up at the resolveVariable(QName qname) call of JSTLXPathVariableResolver.
    What I notice in resolveVariable() call is that qname.getPrefix() is always an empty string. However, qname.getNamespaceURI() returns the proper URI string. In addition, prior to reaching resolveVariable() in JSTLXPathVariableResolver, I do see that the getNamespaceURI() method
    is being called in JSTLXPathNamespaceContext class. However, getPrefix() method of this
    class is never called. My instinct says that if this was called before resolveVariable() method is
    reached (during the creation of QName) I would get a valid prefix instead of an empty string.
    Could someone help with this. Is there something that I am doing wrong. Where does QName
    get created in resolveVariable() and why does it not call getPrefix()
    Please let me know if I can provide more info
    Thanks in advance
    -Dhiru

    The installer extension isn't removed with the application. It still can be found in Java Cache Viewer. When you remove this extension using Java Cache Viewer the uninstall method will be called.
    Is there a way to force the extension uninstallation when the main application is being removed? Removing the very application is user-friendly, you can do it from the Control Panel in Windows. It looks like JWS is missing a very important feature.
    I'm using Java 1.6.0_03 right now.

  • How to search and replace in an xml file using java

    Hi all,
    I am new to java and Xml Programming.
    I have to search and replace a value Suresh with some other name in the below xml file.
    Any help of code in java it is of great help,and its very urgent.
    I am using java swings for generating two text boxes and a button but i am not able to search in the xml file thru the values that are entered into these text boxes.
    Thanks in advance.
    **XML File*
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <student>
    <stud_name>Suresh</stud_name>
    <stud_age>40</stud_age>
    </student>Also i am using SAX Parser in the java program
    any help of code or any tutorials for sax parisng is very urgent please help me to resolve this problem
    Edited by: Karthik84 on Aug 19, 2008 1:45 AM
    Edited by: Karthik84 on Aug 19, 2008 3:15 AM

    Using XPath to locate the elements you are after is very easy.
    Try something like this:
    import java.io.File;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import javax.xml.xpath.XPath;
    import javax.xml.xpath.XPathConstants;
    import javax.xml.xpath.XPathFactory;
    import org.w3c.dom.Document;
    import org.w3c.dom.NodeList;
    import org.xml.sax.InputSource;
    public class BasicXMLReplaceWithDOM4J {
         static String inputFile = "C:/student.xml";
         static String outputFile = "C:/studentRenamed.xml";
         public static void main(String[] args) throws Exception {
              // Read xml and build a DOM document
              Document doc = DocumentBuilderFactory.newInstance()
                        .newDocumentBuilder().parse(new InputSource(inputFile));
              // Use XPath to find all nodes where student is named 'Suresh'
              XPath xpath = XPathFactory.newInstance().newXPath();
              NodeList nodes = (NodeList)xpath
                   .evaluate("//stud_name[text()='Suresh']", doc, XPathConstants.NODESET);
              // Rename these nodes
              for (int idx = 0; idx < nodes.getLength(); idx++) {
                   nodes.item(idx).setTextContent("Suresh-Renamed");
              // Write the DOM document to the file
              Transformer xformer = TransformerFactory.newInstance().newTransformer();
              xformer.transform(new DOMSource(doc), new StreamResult(new File(outputFile)));
    }- Roy

  • Convert String from UTF-8 to IsoLatin1

    Hi everyone !
    I'm trying to convert a String from utf-8 to IsoLatin1, but i got somt problems.... I'm using
    actually this code, but it won't work...
    I'm getting a utf-8 html String with some data and i will write it down in latin1 to a text file
    String newString = new String(oldString.getBytes("UTF-8"), "ISO-8859-1");If i'm now writing this newString to a TextFile it contains cryptic signs like
    & # 1 3 ; or & # 1 3 7 ; or & # 1 2 8 ;(i separated this chars)
    can anyone tell me where is my fault and how can i solve this problem ?
    Thanks a lot
    Edited by: Sephiknight on Feb 23, 2008 2:41 AM

    Yes its XML, i got a web editor where i can add input (utf-8) and i want to write it down in my class to a xml file (isoLatin1).
    My code looks likte this
         public static void setEditFragment(String content, String xPath) throws Exception {
             DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
             DocumentBuilder builder  = factory.newDocumentBuilder();
             Document document = builder.parse("3001300.xml");
             XPath xpath = XPathFactory.newInstance().newXPath();
             Node node = (Node)xpath.evaluate(xPath, document, XPathConstants.NODE);
            Charset charset = Charset.forName("ISO-8859-1");
            CharsetEncoder encoder = charset.newEncoder();    
            ByteBuffer buf = encoder.encode(CharBuffer.wrap(content));
            node.setTextContent(buf.toString()); 
               // Use a XSLT transformer for writing the new XML file
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
             DOMSource        source = new DOMSource( document );
             FileOutputStream os     = new FileOutputStream("tmp.xml");
             StreamResult     result = new StreamResult( os );
             transformer.transform( source, result ); 
         }The example from http://www.exampledepot.com/egs/java.nio.charset/ConvertChar.html looks great, but if I add my own input string i get a exception that looks like this
    java.nio.charset.UnmappableCharacterException: Input length = 1
         at java.nio.charset.CoderResult.throwException(Unknown Source)
         at java.nio.charset.CharsetEncoder.encode(Unknown Source)
         at HagerAbs.setEditFragment(HagerAbs.java:91)
         at HagerAbs.main(HagerAbs.java:108)When i write my input to the xml file it doesnt look like xml at all, it looks more like
    <synthese>& # 13;
    & # 13;
    & lt;br/& gt;& # 13;
    & lt;img class="thumb" src="http: ......{code}
    (i seperated the char so you can see)
    and this is not what i expected... how can i write it down correctly ?
    Edited by: Sephiknight on Feb 23, 2008 3:26 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

Maybe you are looking for

  • VGA card - 2nd display

    Hi! I recently bought and installed on my PC a new VGA graphic card - MSI RX9550-TD256 TV Out/DVI - AGP. I connected the VGA output to the PC monitor, install the drives and it's working fine on the PC monitor. So far, so good. I then connected the D

  • Pdfmaker print driver is missing, I think I accidentally deleted it.

    I cannot create a pdf file from a Word document anymore, I get an error that says teh PDFmaker print driver is missing. I think I accidentally deleted it. What do I do? Can I get just this print driver and install it? Thanks.

  • MacBook Pro 17" airport help (noob)

    I have had a consistant problem with my new macbook. It could be a simple problem that I haven't noticed. I have a 8Mbps connection via a wireless router (linksys). I have gotten a very slow initial connection. I can download files very very fast lik

  • Next song button "sticks"

    I'm wondering why it seems that occasionally while listening to my nano, I am unable to move to the next song while an other song is playing. On these occasions, I can press and press the "skip to the next song" button - and nothing happens. Any idea

  • Two iCloud accounts for work and home?

    On my iPad2, I have a home email account and a work email account and work calendar.  If I set up a second (work) user account on the family iMac, can I have two iCloud accounts to keep work and home separate? I would like to share  pictures, home em