DOM to XML String

Hi,
I'm trying to transform a DOM object into a string of xml, but somehow it only outputs the first line.
What did I do wrong?
          Document doc = processDoc();
          Source source = new DOMSource((Element) doc.getElementsByTagName("vancouver").item(0));
          StringWriter out = new StringWriter();
          StreamResult result = new StreamResult(out);
          Transformer xformer = TransformerFactory.newInstance().newTransformer();
          xformer.setOutputProperty("encoding", "iso-8859-1");
          xformer.setOutputProperty("indent", "yes");
          xformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
          xformer.transform(source, result);
          return result.getWriter().toString();Thanks!
Will

Hi DrClap,
this is how I constructed my DOM object:
     public Document processDoc() throws Exception {
          URL u = new URL("http://www.weatheroffice.ec.gc.ca:80/city/pages/bc-74_metric_e.html");
          DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
          DocumentBuilder builder = factory.newDocumentBuilder();
          // in doc
          Document inDoc = builder.parse(u.openStream());
          // out doc
          Document outDoc = builder.newDocument();
          // grab <div id="citytextf">
          Element inElement = inDoc.getElementById("citytextf");
          Element rootElement = inElement;
          // grab <h2>
          inElement = (Element) inElement.getElementsByTagName("h3").item(0);
          System.out.println(inElement.getTextContent());
          // create output root element
          Element outElement = outDoc.createElement("vancouver");
          outElement.setAttribute("issued", inElement.getTextContent().substring(11));
          rootElement = (Element) rootElement.getElementsByTagName("dl").item(0);
          // iterate thru city <dd>, <dt> tags
          NodeList tempList = rootElement.getElementsByTagName("dt");
          Element tempIn, tempOut;
          for (int i = 0; i < tempList.getLength(); i++) {
               System.out.println(i);
               tempIn = (Element) rootElement.getElementsByTagName("dt").item(i);     // grabs <dt> value
               tempOut = outDoc.createElement("day");
               tempOut.setAttribute("name", tempIn.getTextContent().trim());
               tempIn = (Element) rootElement.getElementsByTagName("dd").item(i);
               String input = tempIn.getTextContent();
               (tempOut.appendChild(outDoc.createElement("high"))).setNodeValue(getHighLowValue("High", input));
               (tempOut.appendChild(outDoc.createElement("low"))).setNodeValue(getHighLowValue("Low", input));
               (tempOut.appendChild(outDoc.createElement("note"))).setNodeValue(getNoteValue(input));
               System.out.println(((Element) tempOut).getAttribute("name"));
               outElement.appendChild(tempOut);
          return outDoc;
     }which is suppose to output XML like this:
<vancouver issued="Issued 6.30 PM PDT Saturday 16 April 2005">
  <day name="Tonight">
    <high></high>
    <low>6</low>
    <note>Cloudy. 60 percent chance of showers. Risk of small hail this evening.</note>
  </day>
  <day name="Sunday">
    <high>12</high>
    <low></low>
    <note>A few showers.</note>
  </day>
  <day name="Monday">
    <high>13</high>
    <low>6</low>
    <note>A mix of sun and cloud.</note>
  </day>
  <day name="Tuesday">
    <high>13</high>
    <low>6</low>
    <note>Sunny</note>
  </day>
  <day name="Wednesday">
    <high>15</high>
    <low>7</low>
    <note>Sunny</note>
  </day>
</vancouver>
      But all it outputs is:
<?xml version="1.0" encoding="iso-8859-1"?>I just started learning XML in Java so there're probably things that I missed out on.
Thanks!

Similar Messages

  • Extracting elements from an xml string - org.apache.xerces.dom.DeferredText

    Hello all,
    I am new to xml, and I thought I had a handle on things until I got this problem...I am getting an xml string from the body of an e-mail message, and then I am trying to extract elements out of it. Here is an example xml string:
    <?xml version="1.0" encoding="UTF-8"?>
    <filterRoot>
       <filter action="MOVE" bool="AND" name="My Saved Filter" target="Deleted Items">
          <condition attribute="TO" bool="AND" contains="CONTAINS">
             <value>[email protected]</value>
             <value>[email protected]</value>
             <value>[email protected]</value>
             <value>[email protected]</value>
             <value>[email protected]</value>
          </condition>
       </filter>
    </filterRoot>I am trying to extract the <filter> element out and store it into a Vector of Elements (called, not surprisingly, filters). However, I am getting a class cast exception:
    java.lang.ClassCastException: org.apache.xerces.dom.DeferredTextImplIt is being called from where I trying to extract the <filter> in this way:
            filterRoot = doc.getDocumentElement(); // get topmost element
            NodeList list = filterRoot.getChildNodes();
            Vector newFilters = new Vector();
            debug("There are "+list.getLength()+" filters in document");
            for(int i=0; i<list.getLength(); i++) {
                Node n = list.item(i);
                debug("Node "+i+" getNodeValue() is "+n.getNodeValue());
                Element temp = (Element)n;
                newFilters.add(temp);
            }Perhaps my question is, how do I correctly get hold of the <filter> node so that I may cast it as an Element?
    thanks,
    Riz

    Yes, I already knew that it is not a bug.
    But, I got next step problem.
    I put "false" to "include-ignorable-whitespace" feature in xerces parser.
    But, I still found unnecessary TextNodes in my parser object.
    Feature link : http://xerces.apache.org/xerces-j/features.html.
    I use xerces-2_8_0.
    DOMParser parser = new DOMParser();
    parser.setFeature("http://apache.org/xml/features/dom/include-ignorable-whitespace", false);
    parser.parse(inputSource);
    document = ps.getDocument();
    System.out.println(document.getDocumentElement().getChildNodes().length()); // still wrong lengthIs tehre any example of usage this feature?
    What is default defination of white-space "\n "(enter with one space) or " "(juz white space) or something else?
    Thanks,

  • XML : Transform DOM Tree to XML String in an applet since the JRE 1.4.2_05

    Hello,
    I build a DOM tree in my applet.
    Then I transform it to XML String.
    But since the JRE 1.4.2_05 it doesn't work.
    These lines failed because these variables became final:
    org.apache.xalan.serialize.CharInfo.XML_ENTITIES_RESOURCE = getClass().getResource("XMLEntities.res").toString();
    org.apache.xalan.processor.TransformerFactoryImpl.XSLT_PROPERTIES = getClass().getResource("XSLTInfo.properties").toString();The rest of the code :
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document domXML = builder.newDocument();
    // I build my DOM Tree
    StringWriter xmlResult = new StringWriter();
    Source source = new DOMSource(domXML);
    Result result = new StreamResult(xmlResult);
    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    xformer.setOutputProperty(javax.xml.transform.OutputKeys.INDENT,"yes");
    xformer.transform(source,result);Is there any other way to get an XML String from a DOM tree in an applet ?
    I'm so disappointed to note this big problem.

    Does anyone have an idea why I get this error message when try to use transform in an applet?
    Thanks...
    java.lang.ExceptionInInitializerError
         at java.lang.Class.forName0(Native Method)
         at java.lang.Class.forName(Unknown Source)
         at org.apache.xalan.serialize.SerializerFactory.getSerializer(Unknown Source)
         at org.apache.xalan.transformer.TransformerIdentityImpl.createResultContentHandler(Unknown Source)
         at org.apache.xalan.transformer.TransformerIdentityImpl.transform(Unknown Source)
         at matrix.CreateMtrx.SaveDoc(CreateMtrx.java:434)
         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 thinlet.Thinlet.invokeImpl(Unknown Source)
         at thinlet.Thinlet.invoke(Unknown Source)
         at thinlet.Thinlet.handleMouseEvent(Unknown Source)
         at thinlet.Thinlet.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    Caused by: java.lang.RuntimeException: The resource [ XMLEntities.res ] could not load: java.net.MalformedURLException: no protocol: XMLEntities.res
    XMLEntities.res      java.net.MalformedURLException: no protocol: XMLEntities.res
         at org.apache.xalan.serialize.CharInfo.<init>(Unknown Source)
         at org.apache.xalan.serialize.SerializerToXML.<clinit>(Unknown Source)
         ... 28 more

  • Problem in parsing a xml string using dom parser

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

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

  • Special charecters handling while Converting XML string to DOM

    Hi,
    I am using the following approach for converting XML string to DOM, but due to Special characters like "&", I am getting Exceptions:
    String xmlString;
    DocumentBuilderFactory factory =
    DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(new InputSource(new StringReader(xmlString)));
    Can anyone please help me out on how to handle the Special characters in the above code.

    If the XML doesn't parse, then the XML must be invalid. Show a sample of such a special character in the XML data. Please use \ tags to post the actual XML content and any other code.                                                                                                                                                                                                                                                                                                                                                                                           

  • How to append an xml string as a child node to a dom document

    Hi
    I have an xml represented as a String. Now I want to add this xml string as a child node to another DOM Document.
    Do I have to first parse the xml String into a xml Document and then add the nodes to the existing Document. Is there a simpler way to do this. Any input is appreciated.
    Many thanks in advance.

    radsat wrote:
    Hi
    I have an xml represented as a String. Now I want to add this xml string as a child node to another DOM Document.
    Do I have to first parse the xml String into a xml Document and then add the nodes to the existing Document. yes, this is what you need to do.
    Is there a simpler way to do this. Any input is appreciated.no, there really isn't, sorry.

  • Convert XML string into DOM

    Hi all,
    I have a question here regarding converting XML string into a DOM document.
    How can I do this in Java?
    The Document.Parse() methods do not have one that takes in String as its parameter.
    I'm not sure what is the best way to do this in Java.
    Any help is greatly appreciated.
    Thank you in advance.
    regards,
    Sean

    Convert XML String to Document with StringReader.
    String xmlString;
    DocumentBuilderFactory factory =
                DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
       Document         document = builder.parse(new InputSource(new StringReader(xmlString)));

  • XML String to DOM object

    Like to conver an xml String such as:
    <books><book>book1</book><book>book2</book2></books>
    to a DOM object
    Thanks

    http://forum.java.sun.com/thread.jsp?forum=34&thread=69283

  • Creating XML String DOM

    Hi ppl,
    I need some help with DOM Object. I have a xml file which I parse with dom and when I do some changes in dom object like adding new element or changing the values of existing object and now when I try to transorm the dom object back to a xml string. It puts everything in one line. for example say my xml file is like:-
    <student>
        <name>john</name>
        <result>pass</result>
    </student>Now when I add new element <address> to it , change value of existing element and try to get xml string i get something like this
    <student><name>smith</name><address>412Miam</address><result>pass</result></student>
    Whole xml in one or two lines, instead of proper xml with one element and its value in one line.
    Any ideas how to achieve this?

    Ddosot,
    Thank you very much. I was looking for this from long time.
    Honeslty I have searched news group many times but couldnt get an answer, may be my search words were not correct.
    you could have saved all this writing by running a
    little search on this forum, as this questions is
    asked once per day.
    anyway, here is your answer:
    transformer.setOutputProperty(OutputKeys.INDENT,
    "yes");
    transformer.setOutputProperty("{http://xml.apache.org/x
    lt}indent-amount", "1");

  • How can i read XML string in a loop???

    i changed xml file reader to xml string reader by
    looking around this and other forums.
    here is the code.
    public class XMLTester2 {
        public static void main(String[] args) {
            String s = "<firsttag><secondtag>123</secondtag></firsttag>";
            java.io.Reader reader = new java.io.StringReader(s);
            org.xml.sax.InputSource source = new org.xml.sax.InputSource(reader);
            org.w3c.dom.Document doc = null;
            javax.xml.parsers.DocumentBuilderFactory fact = javax.xml.parsers.DocumentBuilderFactory.newInstance();
            try {
                javax.xml.parsers.DocumentBuilder builder = fact.newDocumentBuilder();
                doc = builder.parse(source);
            } catch (javax.xml.parsers.ParserConfigurationException pce) {
            } catch (org.xml.sax.SAXException se) {
            } catch (java.io.IOException ioe) {
            } finally {
                try {
                    reader.close();
                } catch (java.io.IOException ignored) {
    }i put this stuff into a loop, but i always ends up
    having new in the loop.
                String inputLine = "Start";
                // define what's needed for XML messages
                Reader reader = new StringReader(inputLine);
                InputSource source = new InputSource(reader);
                Document doc = null;
                DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = null;
                Node xmlNode = null;
                try {
                    builder = fact.newDocumentBuilder();
                } catch (ParserConfigurationException pce) {
                // -->
                while ( (inputLine = in.readLine()) != null) {
                    System.out.println("readLine() : {" + inputLine + "}");
                    reader = new StringReader(inputLine);
                    source.setCharacterStream(reader);
                    try {
                        doc = builder.parse(source);
                    } catch (SAXException se) {
                        System.out.println("SAXException : " + se);
                        System.out.println("SAXException source : " + source.toString() );
                        se.printStackTrace();
                    } catch (IOException ioe) {
                        System.out.println("IOException : " + ioe);
                    } finally {
                        try {
                            reader.close();
                        } catch (IOException ignored) {
                    reader = null;i know putting new in the loop is VERY bad.
    i gotto get ride of this new from the loop.
    can anyone help me?

    i know putting new in the loop is VERY bad.
    i gotto get ride of this new from the loop.Don't design your application based on one-liners you heard somewhere. Do some timings to see if it matters. My guess would be that parsing an XML file would take a fair bit longer than creating a StringReader object. And you do need a new StringReader each time, they aren't reusable, so the alternatives are not obvious. And don't accept my guess about the timings, check it for yourself.

  • Getting Error while creating Document object  after  parsing XML String

    Hi All,
    I have been trying to parse an XML string using the StringReader and InputSource interface but when I am trying to create Document Object using Parse() method getting error like
    [Fatal Error] :2:6: The processing instruction target matching "[xX][mM][lL]" is not allowed.
    seorg.xml.sax.SAXParseException: The processing instruction target matching "[xX][mM][lL]" is not allowed.
    Please find the code below which i have been experimenting with:
    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    import java.io.StringReader;
    import java.util.List;
    import java.util.*;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    import java.io.*;
    public class TestMain {
         public static void main(String[] args) {
              String file = "";
              file = loadFileContent("C:\\Test.xml");
              System.out.println("contents >> "+file);
              parseQuickLinksFileContent(file);
    public static void parseQuickLinksFileContent(String fileContents) {
    PWMQuickLinksModelVO objPWMQuickLinksModelVO = new PWMQuickLinksModelVO();
         try {
    DocumentBuilderFactory factory =           DocumentBuilderFactory.newInstance();
         DocumentBuilder builder = factory.newDocumentBuilder();
         StringReader objRd = new StringReader(fileContents);
         InputSource objIs = new InputSource(objRd);
         Document document = builder.parse(objIs); // HERE I am getting Error.
         System.out.println(document.toString());
    What is happening while I am using builder.parse() method ???
    Thanks,
    Rajendra.

    Getting following error
    [Fatal Error] :2:6: The processing instruction target matching "[xX][mM][lL]" is not allowed.
    seorg.xml.sax.SAXParseException: The processing instruction target matching "[xX][mM][lL]" is not allowed.

  • Digital signature on xml string

    Hello
    I'm trying to sign an xml string, but when I do so, I receive:
    HIERARCHY_REQUEST_ERR: An attempt was made to insert a node where it is not permitted.
         at com.sun.org.apache.xerces.internal.dom.CoreDocumentImpl.insertBefore(Unknown Source)
         at org.jcp.xml.dsig.internal.dom.DOMXMLSignature.marshal(Unknown Source)
         at org.jcp.xml.dsig.internal.dom.DOMXMLSignature.sign(Unknown Source)
         at com.azry.ess.service.mof.InboundMessageUtils.sign(InboundMessageUtils.java:139)
         at com.azry.ess.service.mof.Services.getPaymentString(Services.java:187)
         at com.azry.ess.service.mof.Services.main(Services.java:61)
    the string looks like this:
    <Object Id="PAYMENTS"><PAYMENTS xmlns=""><Payment><PaymentIdA></PaymentIdA><PaymentIdB>aa</PaymentIdB><SrcBank>bb</SrcBank><SrcAccount>cc</SrcAccount><PayerId>dd</PayerId><PayerName>Dato</PayerName><TaxPayerId>00022023</TaxPayerId><TaxPayerName></TaxPayerName><ReceiverName>mof</ReceiverName><AdditinalInfo>racxa</AdditinalInfo><Amount>521</Amount><TreasuryCode>hello</TreasuryCode><PaymentTime>hi</PaymentTime><PaymentChannel>ib</PaymentChannel></Payment></PAYMENTS></Object>
    and here's the code
              XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
              Reference ref = fac.newReference("", fac.newDigestMethod(DigestMethod.SHA1, null));
              CanonicalizationMethod canonicalizationMethod =
                    fac.newCanonicalizationMethod(
                    CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                    (C14NMethodParameterSpec) null);
              SignatureMethod signatureMethod = fac.newSignatureMethod(
                    SignatureMethod.RSA_SHA1, null);
              SignedInfo si = fac.newSignedInfo(
                    canonicalizationMethod, signatureMethod,
                    Collections.nCopies(1, ref));
              KeyInfoFactory kif = fac.getKeyInfoFactory();
              KeyValue kv = kif.newKeyValue(getPeerPublicKey());
              KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
              XMLSignature signature = fac.newXMLSignature(si, ki);
              DOMSignContext sc = new DOMSignContext(getPeerPrivateKey(), doc);
              signature.sign(sc);any ideas? :S
    thanks

    Thanks for the reply
    I'm generating that xml using a simple StringBuilder. here's the code
              StringBuilder sb = new StringBuilder();
              sb.append("<Object Id=\"PAYMENTS\"><PAYMENTS xmlns=\"\"><Payment><PaymentIdA></PaymentIdA><PaymentIdB>");
              sb.append(paymentId);
              sb.append("</PaymentIdB><SrcBank>");
              sb.append(srcBankCode);
              sb.append("</SrcBank><SrcAccount>");
              sb.append(srcBankAccount);
              sb.append("</SrcAccount><PayerId>");
              sb.append(payerId);
              sb.append("</PayerId><PayerName>");
              sb.append(payerName);
              sb.append("</PayerName><TaxPayerId>");
              sb.append(taxPayerId);
              sb.append("</TaxPayerId><TaxPayerName>");
              sb.append("</TaxPayerName><ReceiverName>");
              sb.append(receiverName);
              sb.append("</ReceiverName><AdditinalInfo>");
              sb.append(additionalInfo);
              sb.append("</AdditinalInfo><Amount>");
              sb.append(amount);
              sb.append("</Amount><TreasuryCode>");
              sb.append(treasuryCode);
              sb.append("</TreasuryCode><PaymentTime>");
              sb.append(paymentTime);
              sb.append("</PaymentTime><PaymentChannel>");
              sb.append(paymentChannel);
              sb.append("</PaymentChannel></Payment></PAYMENTS></Object>");
              Document doc = InboundMessageUtils.parseInboundMessage(sb.toString());
              org.w3c.dom.Node n = InboundMessageUtils.sign(InboundMessageUtils.getPeerPrivateKey(), doc);
         public static Document parseInboundMessage(String message) throws Exception {
              DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
              dbf.setNamespaceAware(true);
              InputStream is = new ByteArrayInputStream(message.getBytes(Charset
                        .forName("UTF-8")));
              Document newDoc = dbf.newDocumentBuilder().parse(is);
              return newDoc;
         public static void sign(PrivateKey expectedKey, Document doc) throws Exception{
              XMLSignatureFactory signatureFactory = XMLSignatureFactory
                        .getInstance("DOM");
              XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
              Reference ref = fac.newReference("", fac.newDigestMethod(DigestMethod.SHA1, null));
              CanonicalizationMethod canonicalizationMethod =
                    fac.newCanonicalizationMethod(
                    CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                    (C14NMethodParameterSpec) null);
              SignatureMethod signatureMethod = fac.newSignatureMethod(
                    SignatureMethod.RSA_SHA1, null);
              SignedInfo si = fac.newSignedInfo(
                    canonicalizationMethod, signatureMethod,
                    Collections.nCopies(1, ref));
              KeyInfoFactory kif = fac.getKeyInfoFactory();
              KeyValue kv = kif.newKeyValue(getPeerPublicKey());
              KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
              XMLSignature signature = fac.newXMLSignature(si, ki);
              DOMSignContext sc = new DOMSignContext(getPeerPrivateKey(), doc);
              signature.sign(sc);
         public static PrivateKey getPeerPrivateKey() throws Exception
              BigInteger modulus = new BigInteger(
              "SomeKey");
              BigInteger exponent = new BigInteger("65537");
              RSAPrivateKeySpec spec = new RSAPrivateKeySpec(modulus, exponent);
              PrivateKey key;
              try {
                   KeyFactory kf = KeyFactory.getInstance("RSA");
                   key = kf.generatePrivate(spec);
              } catch (NoSuchAlgorithmException e1) {
                   throw new Exception(e1);
              } catch (InvalidKeySpecException e1) {
                   throw new Exception(e1);
              return key;
         public static PublicKey getPeerPublicKey() throws Exception {
              BigInteger modulus = new BigInteger(
                        "SomeKey");
              BigInteger exponent = new BigInteger("65537");
              RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, exponent);
              PublicKey key;
              try {
                   KeyFactory kf = KeyFactory.getInstance("RSA");
                   key = kf.generatePublic(spec);
              } catch (NoSuchAlgorithmException e1) {
                   throw new Exception(e1);
              } catch (InvalidKeySpecException e1) {
                   throw new Exception(e1);
                   return key;
         }Any idea? :S

  • Java DOM Parser (XML)

    Could someone please give me a link where I can find a example of a DOM parser, w3c. That shows how to parse an xml string or file and build the tree then access parts of it? I cant find a basic example anywhere!

    Check this
    http://java.sun.com/xml/jaxp/dist/1.1/docs/tutorial/dom/1_read.html

  • Parsing an XML string

    How would I get the Oracle XML Parser to parse an XML string?
    The example ("DOMSample") only demonstrates how to parse an XML
    file -- I would like to do something of the form...
    parser.parse("<test>testing</test>");
    On a related note, whilst the PL/SQL utilities are helpful, I
    would like to see more in the way of documentation and examples
    for the Parser itself, showing more examples of DOM API calls and
    perhaps a complete worked example (including a DTD).
    Keep up the good work!
    Many thanks,
    Ian Brettell,
    Indus International.
    null

    Ian Brettell (guest) wrote:
    : How would I get the Oracle XML Parser to parse an XML string?
    : The example ("DOMSample") only demonstrates how to parse an XML
    : file -- I would like to do something of the form...
    : parser.parse("<test>testing</test>");
    With the latest version, 1.0.0.1, now available, you can use the
    InputStream and InputSource methods. Please see the doc for
    details.
    : On a related note, whilst the PL/SQL utilities are helpful, I
    : would like to see more in the way of documentation and examples
    : for the Parser itself, showing more examples of DOM API calls
    and
    : perhaps a complete worked example (including a DTD).
    : Keep up the good work!
    : Many thanks,
    : Ian Brettell,
    : Indus International.
    Thanks for the input. I will pass it onto the documentation team.
    Oracle XML Team
    http://technet.oracle.com
    Oracle Technology Network
    null

  • Parsing XML string with XPath

    Hi,-
    I am trying to parse an XML string with xpath as follows but I am getting null for getresult.
    I am getting java.xml.xpath.xpathexpressionexception at line where
    getresult = xpathexpression.evaluate(isource); is executed.
    What should I do after
    xpathexpression = xPath.compile("a/b");in the below snippet?
    Thanks
    String xmlstring ="..."; // a valid XML string;
    Xpath xpath = XPathFactory.newInstance().newPath();
    xpathexpression = xPath.compile("a/b");
    // I guess the following line is not correct
    InputSource isource = new inputSource(new ByteArrayInputStream(xmlstring.getBytes())); right
    getresult = xpathexpression.evaluate(isource);My xml string is like:
    <a>
      <b>
         <result> valid some more tags here
         </result>
      </b>
      <c> 10
      </c>
    </a>Edited by: geoman on Dec 8, 2008 2:30 PM

    I've never used the version of evaluate that takes an InputSource. The difficulty with using it is that it does not save the DOM object. Each expression you evaluate will have to create the DOM object, use it once and then throw it away. I've yet to write a program that only needs one answer from an XML document. Usually, I use XPath to locate somewhere in a document and then read "nearby" content, add new content nearby, delete content, or move content. I'd suggest you may want to parse the XML stream and save the DOM Document.
    Second, all of the XPath expressions search from a "context node". I have not had good luck searching from the Document object, so I always get the root element first. I think the expression should work if you use the root as the context node. You will need one of the versions of evaluate that uses an Object as the parameter.

Maybe you are looking for

  • Getting the MDX query select error when running a webi report on BI query

    Getting the following error when running a webi report on BI query : A database error occured. The database error text is: The MDX query SELECT  { [Measures].[D8JBFK099LLUVNLO7JY49FJKU] }  ON COLUMNS , NON EMPTY [ZCOMPCODE].[LEVEL01].MEMBERS ON ROWS

  • MRP: how to segregate the planned orders by dependent requirements

    Hello SAP Guru's, I would like to know if this is possible to make the MRP work is this way: - generate global planned orders (by date) for several dependent requirements, for inhouse production; - AND generate individual planned orders for each depe

  • Configuration problem?

    Greetings, this might well be a very stupid question to you who are in the knowing, but this is my problem: I started using servlets (together with the Spring framework) and JSPs using Tomcat 5.5 as the servlet container. I configured everything by h

  • Strange errors in alert log

    Hi, as someone relatively new to Oracle i need some help in identifying some errors in the oracle alert log. ORA-12012: error on auto execute of job 92712 ORA-29282: invalid file ID Thu Mar 14 23:17:50 GMT 2013 I know that nothing should be running a

  • ITunes Match forces download from iCloud when iPhone is attached to my Mac?

    I got iTunes Match just before christmas and I, like a lot of people have been having trouble with the artwork. So I decided to reset my iPhone to wipe all the music off...everything is backed up and I've done this before and it's fixed problems. My