Internal.text parsed by XML object ?

Is it possible to use the XML object to parse internal xml
instead of loading an external file?
I am writing an application that converts arrays &
objects into xml.
In my development, I am displaying the xml in a text field on
the stage. In testing I want to read this text field as a xml file.
Currently I copy and past the xml from flash into the external xml
file (with notepad) then reload the xml file with
sample_xml.load("xml/sample_1.xml");
Can I point to the text field in flash to get the xml parsing
instead of the external file?
Thanks

Actually two ways:
var myXML:XML = new XML(myTextField.text)
or
var myXML:XML = new XML();
//maybe:
myXML.ignoreWhite=true;
//and later...
myXML.parseXML(myTextField.text);

Similar Messages

  • Reading XML object from Request object

    Hi,
    We are using Flash in our web application in which we are sending an XML object using HTTP post method to a JSP where we need to parse the XML object and get the values. Can anyone tell how we can do it?

    In fact we are not getting error in our page. following is the error
    Error: 500
    Location: /team/par/getData10.jsp
    Internal Servlet Error:
    java.lang.IllegalArgumentException
         at javax.servlet.http.HttpUtils.parseQueryString(HttpUtils.java:151)
         at javax.servlet.http.HttpUtils.parsePostData(HttpUtils.java:254)
         at org.apache.tomcat.util.RequestUtil.readFormData(RequestUtil.java:101)
         at org.apache.tomcat.core.RequestImpl.handleParameters(RequestImpl.java:719)
         at org.apache.tomcat.core.RequestImpl.getParameterValues(RequestImpl.java:259)
         at org.apache.tomcat.core.RequestImpl.getParameter(RequestImpl.java:250)
         at org.apache.tomcat.facade.HttpServletRequestFacade.getParameter(HttpServletRequestFacade.java:223)
         at org.apache.jasper.servlet.JspServlet.preCompile(JspServlet.java:437)
         at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:480)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.tomcat.core.ServletWrapper.doService(ServletWrapper.java:405)
         at org.apache.tomcat.core.Handler.service(Handler.java:287)
         at org.apache.tomcat.core.ServletWrapper.service(ServletWrapper.java:372)
         at org.apache.tomcat.core.ContextManager.internalService(ContextManager.java:812)
         at org.apache.tomcat.core.ContextManager.service(ContextManager.java:758)
         at org.apache.tomcat.service.http.HttpConnectionHandler.processConnection(HttpConnectionHandler.java:213)
         at org.apache.tomcat.service.TcpWorkerThread.runIt(PoolTcpEndpoint.java:416)
         at org.apache.tomcat.util.ThreadPool$ControlRunnable.run(ThreadPool.java:501)
         at java.lang.Thread

  • Parse  a XML that is inside  a String Object???

    Hi,
    Will I be able to parse a XML that is stored as a String object rather than using a .XML file.Or is there any other way I would be able to access a XML that comes as a parameter to a method call??
    ~~~~~~~~~~~~~~~~~~~~~
    Java Code:
    public void notify(org.oasisOpen.docs.wsn.x2004.x06.wsnWSBaseNotification12Draft01.NotifyDocument notifyDocument){
    //notifyDocument is a XML Response
              System.out.println("I am from notify" );
              System.out.println(notifyDocument.toString() );
              String notifyString = notifyDocument.toString();
              String s2="<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
              String s3=s2+' '+notifyString;//Want to parse this XML
              System.out.println("******************notifyString"+notifyString);
              System.out.println("******************s2"+s2);
              System.out.println("******************notifyString+S2"+s3);
              //Parse the String S3 which contains a well formed XML(I Checked it)
    try{
              DocumentBuilderFactory dbf =    DocumentBuilderFactory.newInstance();
              DocumentBuilder db = dbf.newDocumentBuilder();
              Document document = db.parse(s3);
    System.out.println("************** After Parsing **********");
            NodeList count = document.getElementsByTagName("wsrf:NewValue");
              int number= count.getLength();
              System.out.println("**********"+number);
              Element f=(Element)count.item(0);
            //NodeList count1= f.getChildNodes();
            NodeList comment=f.getElementsByTagName("safe:Comment");
            int num=comment.getLength();
            System.out.println("******** Len 2********"+num);
            Element f1=(Element)comment.item(0);
              Node n=f1.getFirstChild();
              if(n != null)
              System.out.println("***********8HEllo**********8");
              String s = n.getNodeValue();
              System.out.println("***********"+ s);
              catch(Exception e){
                   System.out.println("*****Exception**********"+e);
       }~~~~~~~~~~~~~~~~~~~~~~~~~`
    Result::
    *****Exception**********java.net.MalformedURLException: no protocol <?xml versi
    on="1.0" encoding="UTF-8"?> <wsn:Notify xmlns:wsn="http://docs.oasis-open.org/ws
    n/2004/06/wsn-WS-BaseNotification-1.2-draft-01.xsd" xmlns:soapenv="http://schema
    s.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns
    :xsi="http://www.w3.org/2001/XMLSchema-instance">
    <wsn:NotificationMessage>
    <wsn:Topic Dialect="http://docs.oasis-open.org/wsn/2004/06/TopicExpression/S
    imple" xmlns:safe="http://ws.apache.org/resource/serena/safe">safe:Comment</wsn:
    Topic>
    <wsn:ProducerReference>
    <add:Address xmlns:add="http://schemas.xmlsoap.org/ws/2003/03/addressing">
    http://10.236.23.86:8080/pubscribe/services/serenasafe</add:Address>
    <add:ReferenceProperties xmlns:add="http://schemas.xmlsoap.org/ws/2003/03/
    addressing">
    <safe:ResourceIdentifier xmlns:safe="http://ws.apache.org/resource/seren
    a/safe">ALF1</safe:ResourceIdentifier>
    </add:ReferenceProperties>
    <add:PortType xmlns:safe="http://ws.apache.org/resource/serena/safe" xmlns
    :add="http://schemas.xmlsoap.org/ws/2003/03/addressing">safe:MySerenaSafePortTyp
    e</add:PortType>
    <add:ServiceName PortName="serenasafe" xmlns:add="http://schemas.xmlsoap.o
    rg/ws/2003/03/addressing"/>
    </wsn:ProducerReference>
    <wsn:Message>
    <wsrf:ResourcePropertyValueChangeNotification xmlns:wsrf="http://docs.oasi
    s-open.org/wsrf/2004/06/wsrf-WS-ResourceProperties-1.2-draft-01.xsd">
    <wsrf:OldValue>
    <safe:Comment xmlns:safe="http://ws.apache.org/resource/serena/safe">c
    omment</safe:Comment>
    </wsrf:OldValue>
    <wsrf:NewValue>
    <safe:Comment xmlns:safe="http://ws.apache.org/resource/serena/safe">Q
    uick test!</safe:Comment>
    </wsrf:NewValue>
    </wsrf:ResourcePropertyValueChangeNotification>
    </wsn:Message>
    </wsn:NotificationMessage>
    </wsn:Notify>

    Submitting a string is the equivalent of telling the document builder to fetch the XML from a given URI. If you already have the string in memory:
    DocumentBuilder db = null;  // initialize in a spiffy way
    Document document = db.parse(new StreamSource(new ByteArrayInputStream(xml.getBytes()));- Saish

  • DocumentBuilder parser, DOM doucment object from a XML file error

    Hi guys
    I created a program which parses a xml and creates a DOM document object from
    it. The parser is validating.
    class xmlParser
        //create arrylist to store employee in
        private ArrayList<Employee> employeeStore = new ArrayList<Employee>();
        private DocumentBuilder parser;
        private static Document document;     
        //create an instant of Employee to be added to the arraylist
        private Employee theEmployee = new Employee();
        //create an instant of Address to be added to Employee to again be
        //added to Employee
        private Address employeeAddress = new Address();
        public xmlParser()
        public xmlParser(String myfile) throws IOException 
              //validate the XML document agaisnt the given dtd
              DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
              factory.setValidating(true);
              factory.setIgnoringElementContentWhitespace(true);
              try {
                  parser = factory.newDocumentBuilder();
              }catch(javax.xml.parsers.ParserConfigurationException d) {
                   System.out.println("error with new document builder");
              //create document object (DOM tree) from xml file
              try {
                  document = parser.parse(new File(myfile));
              }catch(org.xml.sax.SAXException e) {
                  System.out.println("Error with parser file still creating xml personnel2");
        } In my main method when i call:
    xmlParser parsertree = new xmlParser("personnel.xml"); the exception keeps getting thrown and i get my my message back "Error with parser file still creating xml personnel2"
    Can't seem to figure it out, any ideas would be great.
    Thanks alot

    Hi,
    A - Check that the xml file is located in the same directory where you
    run your app.
    B - Check that the xml file is correct (in XML way).
    Suggestion : you may print the exception message, it might help.
    Hope that help,
    Jack

  • Replace text in XML object using a sequence of tags as input

    Hi, I need to write an apparently very simple function that replaces a text between tags in an XML object receving as input the sequence of tags to identify the element, but I miss one point.
    I travel through the XML tree using a element variable like
    Code:
    element = element.child(n)
    using at each step the tags provided as input to decide the value of "n". Now, when I reach the tags that contain the text to be replaced, what to do? If I use
    Code:
    element.replace(0, newValue)
    I replace the text just in element  not in the original object...
    For example having
    <publishing_date>
           <year>2002</year>
           <month>Jan</month>
    <success_date>
           <year>2004</year>
           <month>Feb</month>
    </success_date>
    I want to call a function like
    replace(["success_date", "month"], "Mar")
    and have an XML object where the second occurence of Feb is replaced with "Mar"
    Any suggestion on this easy task?
    Thanks a lot
    Giuse

    Hi Michael, thanks but my question was difference.
    I need to make a function to operate with input tags, not with known tags. So I am writing a loop that scans the XML object using the tags provided in input until it reaches the desired tag with the text to be replaced.
    That's why I wrote
    element = element.child(n)
    that I was thinking to use at each step of the loop looking for desired tag.
    There I have the problem: if I use
    element.replace.... I am changing the text between the tags in the element variable, not in the original XMLObject, and since there are no pointers in JavaScript, how to do that?
    I hope to have been more clear now..... did I ?
    Thanks and best reagrds
    Giuseppe

  • "Error while parsing SOAP XML payload: no element found" received when invoking Web Service

    Running PB 12.1 Build 7000.  Using Easysoap.  Error ""Error while parsing SOAP XML payload: no element found" received when invoking Web Service".  This error does not appear to be coming from the application code.  Noticed that there were some erroneous characters showing up within the header portion of the XML ("&Quot;").  Not sure where these are coming from.  When I do a find within the PB code for ""&quot;" it gets located within two objects, whereas they both reference a "temp_xml_letter".  Not sure where or what temp_xml_letter resides???   The developer of this is no longer with us and my exposure to WSDL and Web Services is rather limited.  Need to get this resolved...please.
    This is the result of the search.  Notice the extraneous characters ("&quot;"):
    dar1main.pbl(d_as400_mq_xml)
    darlettr.pbl(d_email_xml)
    ---------- Search: Searching Target darwin for 'temp_xml'    (9:52:41 AM)
    ---------- 2 Matches Found On "temp_xml":
    dar1main.pbl(d_as400_mq_xml).d_as400_mq_xml:  export.xml(usetemplate="temp_xml_letter" headgroups="1" includewhitespace="0" metadatatype=0 savemetadata=0  template=(comment="" encoding="UTF-8" name="temp_xml_letter" xml="<?xml version=~"1.0~" encoding=~"UTF-16LE~" standalone=~"yes~"?><EmailServiceTransaction xmlns=~"http://xml.xxnamespace.com/Utility/Email/EmailService" ~" xmlns:imc=~"http://xml.xxnamespace.com/IMC~" xmlns:xsi=~"http://www.w3.org/2001/XMLSchema-instance~" xmlns:root=~"http://xml.xxnamespace.com/RootTypes~" xmlns:email=~"http://xml.xxnamespace.com/Utility/Email~" xsi:schemaLocation=~"http://xml.xxnamespace.com/Utility/Email/EmailService http://dev.xxnamespace.com/Utility/Email/EmailService/V10-TRX-EmailService.xsd~"><EmailServiceInformation><EmailServiceDetail __pbband=~"detail~"><ApplicationIdentifier> applicationidentifier </ApplicationIdentifier><AddresseeInformation><AddresseeDetail><Number> number </Number></AddresseeDetail></AddresseeInformation><EmailMessageInformation><Ema
    darlettr.pbl(d_email_xml).d_email_xml:  export.xml(usetemplate="temp_xml_letter" headgroups="1" includewhitespace="0" metadatatype=0 savemetadata=0  template=(comment="" encoding="UTF-8" name="temp_xml_letter" xml="<?xml version=~"1.0~" encoding=~"UTF-16LE~" standalone=~"yes~"?><EmailServiceTransaction xmlns=~"http://xml.xxnamespace.com/Utility/Email/EmailService" ~" xmlns:imc=~"http://xml.xxnamespace.com/IMC~" xmlns:xsi=~"http://www.w3.org/2001/XMLSchema-instance~" xmlns:root=~"http://xml.xxnamespace.com/RootTypes~" xmlns:email=~"http://xml.xxnamespace.com/Utility/Email~" xsi:schemaLocation=~"http://xml.xxnamespace.com/Utility/Email/EmailService http://dev.xxnamespace.com/Utility/Email/EmailService/V10-TRX-EmailService.xsd~"><EmailServiceInformation><EmailServiceDetail __pbband=~"detail~"><ApplicationIdentifier> applicationidentifier </ApplicationIdentifier><AddresseeInformation><AddresseeDetail><Number> imcnumber </Number></AddresseeDetail></AddresseeInformation><EmailMessageInformation><Ema
    ---------- Done 2 Matches Found On "temp_xml":
    ---------- Finished Searching Target darwin for 'temp_xml'    (9:52:41 AM)

    Maybe "extraneous" is an incorrect term.  Apparantly, based upon the writeup within Wiki, the parser I am using does not interpret the "&quot;"?  How do I find which parser is being utilized and how to control it?
    <<<
    If the document is read by an XML parser that does not or cannot read external entities, then only the five built-in XML character entities (see above) can safely be used, although other entities may be used if they are declared in the internal DTD subset.
    If the document is read by an XML parser that does read external entities, then the five built-in XML character entities can safely be used. The other 248 HTML character entities can be used as long as the XHTML DTD is accessible to the parser at the time the document is read. Other entities may also be used if they are declared in the internal DTD subset.
    >>>

  • Error in Get Next Non-Text Sibling for XML without CR at end of tag

    Hallo all,
    I'm having a strange error parsing XML files with labview. I have an XML file in one single line, without CR at end of each tag. A normal browser or XML parsing tool is capable to read it, but not with Labview.
    The error I have is with "Get Next Non-Text Sibling.vi", which internally fails to read Type property (Error -2630, Property Node (arg 1) in NI_XML.lvlib:Get Next Non-Text Sibling.vi->XML Get Siblings Childs Nodes.vi->Encode data to label (Path).vi).
    Labview XML parser works if I add a CR at each tag/node.
    I'm quite sure this is a labview bug. A workaround I have found is to open the file, then save the file with Save File (Pretty Print) method and reopen it again, but it is time-consuming and I would like to avoid it.
    Regards,
    Daniele
    Solved!
    Go to Solution.
    Attachments:
    xmlwithnoCR.xml.txt ‏1 KB

    Which node do you pass to XML Get Siblings Child Nodes.vi ? That is also important.
    I can imagine the following scenario causing your problem: Your input node has a child node C,, but this child node has no siblings. Get Next Non-Text Sibling.vi will fail in this case. If you put a <CR> at the right position in your XML you create a text node with content <CR>. If this text node is a sibling of child C then Get Next Non-Text Sibling.vi still won't return anything but no error should occur. IMHO this is expected behavior. You can however implement your own version of Get Next Non-Text Sibling.vi. Use the Next Sibling property and check if it returns a valid refnum.

  • Parsing an XML doc with unavailable entity (DTD)

    Hi all,
    I am trying to parse an XML file (web.xml) that has the following DOCTYPE in the head of the document:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
    <web-app id="WebApp">When the parser starts, it will look for the DTD on the Sun site, however my work firewall blocks access to this so I get an exception when parsing.
    To resolve this, I have tried to force the parser to look for a local copy of the DTD instead of the Sun site but to no avail. I still get the same error but don't know why it wont look at the local DTD.
    Here is my code:
    * InterceptingXml.java
    * Created on 04 April 2006, 15:58
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package org.xmldemos;
    import java.io.File;
    import java.io.FileReader;
    import java.io.IOException;
    import java.net.URI;
    import java.net.URISyntaxException;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import org.w3c.dom.Document;
    import org.xml.sax.EntityResolver;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    * @author CS781RJ
    public class InterceptingXml
        /** Creates a new instance of InterceptingXml */
        public InterceptingXml() { }
        public void parse(String filename)
            try
                // Create an XML parser
                DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                // Install the entity resolver
                builder.setEntityResolver(new MyResolver());
                // Parse the XML file
                Document doc = builder.parse(new File(filename));
            catch (SAXException e) { e.printStackTrace(); }
            catch (ParserConfigurationException e) { e.printStackTrace(); }
            catch (IOException e) { e.printStackTrace(); }
            catch (Exception e) { e.printStackTrace(); }
        public class MyResolver implements EntityResolver
            // This method is called whenever an external entity is accessed
            // for the first time.
            public InputSource resolveEntity(String publicId, String systemId)
                try
                    System.out.println("publicId: " + publicId + " systemId: " + systemId);
                    // Wrap the systemId in a URI object to make it convenient
                    // to extract the components of the systemId
                    URI uri = new URI(systemId);
                    System.out.println("URI scheme: " + uri.getScheme());
                    System.out.println("URI scheme specific: " + uri.getSchemeSpecificPart());
                    // Check if external source is a file
                    if ("http".equals(uri.getScheme()))
                        String filename = uri.getSchemeSpecificPart();
                        filename = "file:/C:/web-app_2_3.dtd";
                        InputSource isrc = new InputSource(new FileReader(filename));
                        return isrc;
                catch (URISyntaxException e) { }
                catch (IOException e) { }
                // Returning null causes the caller to try accessing the systemid
                return null;
        public static void main(String[] args)
            InterceptingXml ixml = new InterceptingXml();
            ixml.parse("c:\\web.xml");
    }And here is the exception:
    init:
    deps-jar:
    compile-single:
    run-single:
    publicId: -//Sun Microsystems, Inc.//DTD Web Application 2.3//EN systemId: http://java.sun.com/dtd/web-app_2_3.dtd
    URI scheme: http
    URI scheme specific: //java.sun.com/dtd/web-app_2_3.dtd
    java.net.UnknownHostException: java.sun.com
            at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:177)
            at java.net.Socket.connect(Socket.java:507)
            at java.net.Socket.connect(Socket.java:457)
            at sun.net.NetworkClient.doConnect(NetworkClient.java:157)
            at sun.net.www.http.HttpClient.openServer(HttpClient.java:365)
            at sun.net.www.http.HttpClient.openServer(HttpClient.java:477)
            at sun.net.www.http.HttpClient.<init>(HttpClient.java:214)
            at sun.net.www.http.HttpClient.New(HttpClient.java:287)
            at sun.net.www.http.HttpClient.New(HttpClient.java:299)
            at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:792)
            at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:744)
            at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:669)
            at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:913)
            at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(XMLEntityManager.java:973)
            at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.startEntity(XMLEntityManager.java:905)
            at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.startDTDEntity(XMLEntityManager.java:872)
            at com.sun.org.apache.xerces.internal.impl.XMLDTDScannerImpl.setInputSource(XMLDTDScannerImpl.java:282)
            at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$DTDDispatcher.dispatch(XMLDocumentScannerImpl.java:1021)
            at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:368)
            at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:834)
            at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:764)
            at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:148)
            at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:250)
            at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:292)
            at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:172)
            at org.xmldemos.InterceptingXml.parse(InterceptingXml.java:45)
            at org.xmldemos.InterceptingXml.main(InterceptingXml.java:88)
    BUILD SUCCESSFUL (total time: 18 seconds)I have noticed that return isrc; does not get executed even though the debugger steps to the line above it.
    Thanks in advance.
    Riz

    What's the point of all that code in your EntityResolver? Would the code work just as well if the DTD didn't even exist? Then do this:public InputSource resolveEntity(String publicId, String systemId)
                return new InputSource(new StringReader(""));
            }However if you really do need to redirect to a local copy of the DTD then consider this:catch (IOException e) { }can be a real barrier to understanding in the case that an IOException is thrown. At least print a stacktrace. And: the FileReader class wants a file name in its constructor, not a URI. And in this code:String filename = uri.getSchemeSpecificPart();
    filename = "file:/C:/web-app_2_3.dtd";you could write this instead:String filename = "file:/C:/web-app_2_3.dtd";which would be both shorter and easier to understand.

  • How to parse large xml file

    I need to parse large xml file which contains following tag. The size of the file is upto 10MB-50MB or more.
    <departments>
    <department>
    <a_depart id="124">
    <b_depart id="Bss_253">
    <bss_depart id="253">
    <attributes>
    <name_one>abc</name_one>
    </attributes>
    </bss_depart id="253">
    </b_depart id="Bss_253">
    </a_depart id="124">
    </department>
    <department>
    <a_depart id="124">
    <b_depart id="Bss_254">
    <mss_depart id="253">
              <attributes>
              <name_one>abc</name_one>
              <name_two>xyz</name_one>
              </attributes>
         </mss_depart>
         </b_depart>
    </a_depart>
    </department>
    <department>
    <a_depart id="124">
    <b_depart id="Bss_254">
    <mss_depart id="255">
              <attributes>
              <name_one>abc</name_one>
              <name_two>xyz</name_one>
              </attributes>
         </mss_depart>
         </b_depart>
    </a_depart>
    </department>
    <department>
    <a_depart id="125">
    <b_depart id="Bss_254">
    <mss_depart id="253">
              <attributes>
              <name_one>abc</name_one>
              <name_two>xyz</name_one>
              </attributes>
         </mss_depart>
         </b_depart>
    </a_depart>
    </department>
    I want to get the infomation for that xml file. like mss_depart id=233, building xpath dyanmically for every id and loading
    that using dom4j. which is very very slow.
    Is there any other solution for that to read the data using sax parser only.
    I want to execute the xpath or data for the following way.
    //a_depart/@id ------> all the ids of a_depart tags if it returns 3 values say 123,124,125
    after that i want to execute
    //a_depart[@id='123']/b_depart/@id like this ...to retrive the values of all the levels ...
         I am executing following xpath for every unique ids at all levels.
         List l = doc.selectNodes(xPathForID);
         List l1 = doc.selectNodes(xPathForAttributes+attributes.get(j)+"/text()");
    But it is very slow and taking lot of time.
    Is there any other way to solve this problem. If any please mail me it is urgent.
    I am using jdk1.4 and jdk1.5
    Is there any support for sax parser to execute xpath in jdk1.5 direclty, with out using dom4j
    Thanks in advance....

    I doubt you will find a preexisting solution to your problem.
    SAX is usually recommended for processing big files (where "big" is undefined"). It works on big files by avoiding the messy problem of storing the data -- that is left as an exercise to you.
    DOM (and its variants) works by building a Document object as the head of the tree of objects for the entire contents. With DOM, you can then use XPath, because there is something to search that is already in memory. To use XPath, you seem to have two choices, build a DOM-ish tree, or if you can find an XPath processor (I'm not sure if one exists) that can process the XML file directly, but it will be slow, since you are looking for "all" occurences of an attribute, and this means you have to read the entire file each time.
    It might be worth exploring a hybrid approach -- use SAX to get some information, and build your own objects to store the data. Maybe a HashMap as the main index. But, that will keep you from using XPath, since you do not have the data structures it expects.
    A third alternative would be to look at JAXB. It builds Java code from a Schema of your data and then when you import the data, it creates the necessary objects and fills in values. But, I don't think XPath woll work there either.
    Dave Patterson

  • Passing data from an XML object to an itemRenderer

    I'm trying to color the background of a column in a datagrid and have found a sample file that illustrate the concept. However, the sample has data stored in an arrayCollection whereas mine is in an XML object. The problem is that the data in the sample file is apparently automatically passed to the itemRenderer (shown below: note the trace statement). My XML object does not appear to automatically pass data to the itemRenderer. So my questions are:
    1. Is there a simple way to pass data stored in an XML object to an itemRenderer
    or
    2. Should I convert my XML to an arrayCollection? If so, what's the best way to do this-- I've tried the following, but without success:
    <mx:Model id="xmldata" source="example3.xml"/>
      <mx:ArrayCollection id="myAC" source="{ArrayUtil.toArray(xmldata.Example1)}" />
    Here's what the xml looks like:
    <TABLE>
       <EXAMPLE1>
          <difficulty> 0.5 </difficulty>
          <discrimination> 0.7 </discrimination>
          <item> 3 </item>
       </EXAMPLE1>
    </TABLE>  
    Here's the itemRenderer:
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Label xmlns:mx="http://www.adobe.com/2006/mxml">
        <!--
            This item renderer simply extends Label and overrides the updateDisplayList function to
            draw a gradient-filled rectangle. The colors in the gradient are determined from the
            data.
        -->
        <mx:Script>
        <![CDATA[
            import flash.geom.Matrix;
            import flash.display.GradientType;
            import flash.display.Graphics;
            override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
                super.updateDisplayList(unscaledWidth,unscaledHeight);
                var m:Matrix = new Matrix();
                m.createGradientBox(unscaledWidth,unscaledHeight);
                var g:Graphics = graphics;
                            trace("data.col3="+data.col3)
                var colors:Array = (data.col3 < 2000 ? [0x0000CC,0x0000FF] : [0x00CC00,0x00FF00]);
                g.clear();
                g.beginGradientFill(GradientType.LINEAR, colors, [0.2,0.6], [0,255], m);
                // the rectangle is drawn a little high and a little tall to compensate for the gap
                // the DataGrid introduces between rows.
                g.drawRect(0, -2, unscaledWidth, unscaledHeight+4 );
                g.endFill();
        ]]>
        </mx:Script>
    </mx:Label>

    This sample code should answer your question of how to bring data into the renderer automatically. It comes in via the DataGrid dataProvider and then you refer to it in the renderer as data.XYZ, where XYZ is the field in the XML with the data. See FB 3 help sys on e4x syntax.
    ------------------ mainapp.mxml --------------------
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
      creationComplete="srvc.send();">
      <mx:Script>
        <![CDATA[
          import mx.rpc.events.ResultEvent;
          import mx.collections.XMLListCollection;
          [Bindable] private var xlc:XMLListCollection;
          private function dataHandler(evt:ResultEvent):void{
            xlc = new XMLListCollection(evt.result..EXAMPLE1 as XMLList);
        ]]>
      </mx:Script>
      <mx:HTTPService id="srvc" url="data2.xml" result="dataHandler(event)"
        resultFormat="e4x"/>
      <mx:DataGrid dataProvider="{xlc}">
        <mx:columns>
          <mx:DataGridColumn headerText="Difficulty" dataField="difficulty"/>
          <mx:DataGridColumn headerText="Discrimination" dataField="discrimination"/>
          <mx:DataGridColumn headerText="Item" itemRenderer="MyLabel"/>
        </mx:columns>
      </mx:DataGrid>
    </mx:Application>
    ----------- MyLabel.mxml --------------
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Label xmlns:mx="http://www.adobe.com/2006/mxml">
      <mx:Script>
        <![CDATA[
          import flash.geom.Matrix;
          import flash.display.GradientType;
          import flash.display.Graphics;
          override protected function updateDisplayList(unscaledWidth:Number,
            unscaledHeight:Number):void{
            super.updateDisplayList(unscaledWidth,unscaledHeight);
            this.text = data.col3;
            var m:Matrix = new Matrix();
            m.createGradientBox(unscaledWidth,unscaledHeight);
            var g:Graphics = graphics;
            var colors:Array = (data.col3 < 2000 ? [0x0000CC,0x0000FF] : [0x00CC00,0x00FF00]);
            g.clear();
            g.beginGradientFill(GradientType.LINEAR, colors, [0.2,0.6], [0,255], m);
            g.drawRect(0, -2, unscaledWidth, unscaledHeight+4 );
            g.endFill();
        ]]>
      </mx:Script>
    </mx:Label>
    ------------ data2.xml ----------------
    <?xml version="1.0" encoding="utf8"?>
    <TABLE>
       <EXAMPLE1>
          <difficulty> 0.5 </difficulty>
          <discrimination> 0.7 </discrimination>
          <col3> 3 </col3>
       </EXAMPLE1>
    </TABLE>

  • Unable to display tree view; Error when parsing an XML document (Premature end of file.)

    Hi folks,
    I am using a cascaded mapping in my OM. I have a graphical mapping followed by the Java mapping. It is a flat file to IDOC mapping. Everything works fine in Dev but when I transport the same objects to QA, the Operation mapping though it doesn't fail in ESR testing tool, gives the following message and there is no output generated for the same payload which is successfully tested in DEV. Please advise on what could be the possible reasons.
    Unable to display tree view; Error when parsing an XML document (Premature end of file.)

    kalyan,
    There seems to be an invalid xml payload which causes this error in ESR not generating the tree view. Please find the similar error screenshot and rectify the payload.
    Mutti

  • Parseing an XML Document as a String

    Hi all,
    i am trying to parse an XML document to a parser. I get the file as a request parameter, which is filled in to at String variable.
    But for some reason i get an SAXException, does anyone se the problem?
    Thank you for your help...
    Below is the code
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.*;
    import java.text.*;
    import java.net.*;
    import java.net.URL;
    import java.sql.*;
    import org.w3c.dom.Document;
    import org.w3c.dom.NamedNodeMap;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    import javax.xml.parsers.*;
    import javax.xml.transform.stream.StreamSource;
    public class StartServlet extends HttpServlet
    private boolean debug = true;
    private final static String CONTENT = "content";
    private final static String COOKIES = "cookies";
    String resp = new String();
    private static String NODE_TYPES[] = new String[] {
         "ELEMENT",
         "ATTRIBUTE",
         "TEXT",
         "CDATA_SECTION",
         "ENTITY_REFERENCE",
         "ENTITY",
         "PROCESSING_INSTRUCTION",
         "COMMENT",
         "DOCUMENT",
         "DOCUMENT_TYPE",
         "DOCUMENT_FRAGMENT",
         "NOTATION" };
    public static void println(String s, int indent) {
         for(int i = 0 ; i < indent; i++) {
                   System.out.println(" ");
         System.out.println(s);
    public static void println(String s) {
         System.out.println(s);
    public static void print(Node node){
         printImpl(node, 0);
    public static void printImpl(Node node, int indent){
         if(node == null) {
              return;
         String nodeType = NODE_TYPES[node.getNodeType()];
         String nodeName = node.getNodeName();
         String nodeValue = node.getNodeValue();
         if(nodeValue != null) {
              nodeValue = nodeValue.trim();
         if(nodeType.equals("TEXT") && nodeValue.equals("")) {
              ; //Ignore emty node
         else {
              println(nodeType + " - " + nodeName + " - " + nodeValue, indent);
         NamedNodeMap attributes = node.getAttributes();
         if (attributes != null) {
              for(int i = 0; i < attributes.getLength(); i++) {
                   printImpl(attributes.item(i), indent + 1);
         NodeList children = node.getChildNodes();
         if(children != null) {
              for(int i = 0; i < children.getLength(); i++){
                   printImpl(children.item(i), indent + 1);
    public static DocumentBuilder newBuilder(boolean validation)
                        throws ParserConfigurationException {
         DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
         domFactory.setValidating(validation);
         domFactory.setNamespaceAware(true);
         DocumentBuilder domBuilder = domFactory.newDocumentBuilder();
         //domBuilder.setErrorHandler(new PrintErrorHandler());
         return domBuilder;
    public static Document newDocument()
                        throws ParserConfigurationException{
         DocumentBuilder domBuilder = newBuilder(false);
         Document document = domBuilder.newDocument();
         return document;
    public static Document parse( String xml, boolean validation)
                        throws ParserConfigurationException, IOException, SAXException {
              DocumentBuilder domBuilder = newBuilder(validation);
              Document document = domBuilder.parse(xml);
              return document;
    public void init() {
    public void service( javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse res) {
              String[] cookies = null;
              try{
                   Hashtable document = getDocument("http://.../first.xml", cookies);
                   resp = (String) document.get(CONTENT);
                   debug(resp);
                   print(parse(resp, false));
              catch (SAXParseException e){
                   System.out.println("Saxfejl");
                   //System.exit(1);
              catch (Exception e){
                   e.printStackTrace();
                   System.exit(1);
    public void debug(String msg) {
         if(debug) {
              System.out.println(msg);
    public void performTask(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) {
         try
              // Insert user code from here.
         catch(Throwable theException)
              // uncomment the following line when unexpected exceptions
              // are occuring to aid in debugging the problem.
              //theException.printStackTrace();
    public void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException {
         performTask(request, response);
    public void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException {
         performTask(request, response);
    private Hashtable getDocument(String urlCode, String[] oldCookies) {
         Hashtable document = new Hashtable();
         HttpURLConnection http = null;
         try {
              URL httpURL = new URL(urlCode);
              // If HTTP Protocol, then open connection using the Request method indicated
              URLConnection conn = httpURL.openConnection();
              http = (HttpURLConnection) conn;
              //http.setRequestMethod("GET");
              http.setDoInput(true);
              http.setDoOutput(true);
              http.setUseCaches(false);
              http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
              if (oldCookies != null) {
                   for (int j = 0; j < oldCookies.length; j++) {
                        String cookie = oldCookies[j];
                        http.setRequestProperty("Cookie", cookie);
              http.connect();
              http.getContent();
              StringBuffer tsb = new StringBuffer("");
              if (http.getResponseCode() == 200) {
                   InputStream cis = http.getInputStream();
                   byte[] a = new byte[1024];
                   int n = cis.read(a);
                   while (n >= 0) {
                        tsb.append(new String(a, 0, n));
                        n = cis.read(a);
                   cis.close();
                   document.put(CONTENT, tsb.toString());
              String[] cookies = null;
              if (cookies == null) {
                   int headerFieldIndex = 0;
                   String headerFieldValue = http.getHeaderField(headerFieldIndex);
                   Vector cookieValues = new Vector();
                   while (headerFieldValue != null) {
                        String headerFieldName = http.getHeaderFieldKey(headerFieldIndex);
                        if ((headerFieldName != null) && headerFieldName.toLowerCase().equals("set-cookie")) {
                             int index = headerFieldValue.indexOf(";");
                             if (index > -1) {
                                  headerFieldValue = headerFieldValue.substring(0, index);
                             cookieValues.addElement(headerFieldValue);
                        headerFieldValue = http.getHeaderField(++headerFieldIndex);
                   cookies = new String[cookieValues.size()];
                   cookieValues.copyInto(cookies);
              document.put(COOKIES, cookies);
         catch (Exception e) {
              debug("url problem" + e);
         finally {
              if (http != null) {
                   http.disconnect();
         return document;
    }

    Hi,
    Use this code it will helpful to you.
    resultXMLDocument=(XmlDocument)documentDoc;
    StringWriter sw = new StringWriter();
    resultXMLDocument.write((Writer) sw);
    xmlString=sw.toString();
    thnaks,
    suneel

  • Calling Bpel Process From a Jsp(Need a string output instead of XML object)

    Hi
    I am calling a BPEL process(Synchrononus) from a JSP page, Where Bpel process calls a java web service.The output from Bpel process is returned as an XML object. I need the output in a string format.Please let me know the steps to get the string output.
    I also executed invokeCreditRatingService.jsp(from samples shipped with SOA Suite) that calls CreditRatingService bpel, but i was getting the following output where the rating value is printed as an XML object.
    Output:-
    BPELProcess CreditRatingService executed!
    Credit Rating is oracle.xml.parser.v2.XMLElement@9511c8
    Please let me know, what changes i need to make to get the string output.I followed all the steps given in "orabpel-Tutorial7-InvokingBPELProcesses.PDF" to execute credit rating jsp.
    We are using SOA Suite 10.1.3.1.0 version.Do I need to make any changes to the code, to make it work with this version.
    Thanks
    Vandana.

    The call payload.get("payload") returns, as you have observed, an XMLElement. You can simply convert the XMLElement into an XML string by using a DOMSerializer implementation. The following code is very useful for this purpose:
    http://javafaq.nu/java-example-code-432.html
    Best,
    Manfred

  • Can someone help me with a problem of parsing an XML file?

    Hello,
    I'm having some problems parsing an xml file. I get a SAXNotSupportedException when setting a property value.
    Here is the piece of code where I have the problem:
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);
    SAXParser saxParser = spf.newSAXParser();
    XMLReader xmlReader = saxParser.getXMLReader();
    DefaultHandler defHandler = new DefaultHandler();
    xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", defHandler);
    and the log is:
    Problem with the parser org.xml.sax.SAXNotSupportedException: PAR012 For propertyID "http://xml.org/sax/properties/lexical-handler", the value "org.xml.sax.helpers.DefaultHandler@4ff4f74a" cannot be cast to LexicalHandler.
    http://xml.org/sax/properties/lexical-handler org.xml.sax.helpers.DefaultHandler@4ff4f74a LexicalHandler
    I've been working on this problem but I can't find the error.
    Does anyone have an idea of what to do to solve it?
    Thanx in advance,
    M@G

    before deciding which XML technology to use, you should see if your application fit in the category below:
    use SAX:
    1. The XML file is rather large (30 or 40+ MB)
    2. I don't need the xml document in memory. I will parse the document and store the data in my own object.
    use DOM or JDOM
    1. The XML file is relatively small (less than 30 MB) or I can increase the runtime memory for larger xml file.
    2. I will need to walk up and down the xml document tree severals time.
    3. My application is in Java and it's not going to be rewritten in C++, etc (use JDOM)
    NOTE:
    JDOM is rather easier to use (for Java developer), but it's not an www.org.com standardlized xml parser.
    personally, i like JDOM for traversing the DOM.

  • How can i filter an xml object on an attribute?

    I want address an xml object with .(@ attributeNameHere == "textToSearchForHere") and have it return the node it’s associated with. 
    This is the text from the adobe help site and it’s similar to my actual code.  I’m querying this xml object: staticVar.employee.(@id=="347").  FlashBuilder 4.7 is returning an error “No such variable: @id”. when I look in debugger.
    This example is found in Adobe's help site: Adobe Flash Platform * Traversing XML structures
    The help site says
    The following expressions are all valid:
    x.employee.(lastName == "McGee")—This is the secondemployeenode.
    x.employee.(lastName == "McGee").firstName—This is thefirstNameproperty of the secondemployeenode.
    x.employee.(lastName == "McGee").@id—This is the value of theidattribute of the secondemployeenode.
    x.employee.(@id == 347)—The firstemployeenode.
    public var staticVar:XML = 
    <employeeList>
          <employee id="347">
               <lastName>Zmed</lastName>
               <firstName>Sue</firstName>
               <position>Data analyst</position>
          </employee>
          <employee id="348">
               <lastName>McGee</lastName>
               <firstName>Chuck</firstName>
               <position>Jr. data analyst</position>
          </employee>
    </employeeList>;
    I’m expecting this: staticVar.employee.(@id=="347") will return the following node:
    <employee nu="347">
    <lastName>Zmed</lastName>
    <firstName>Sue</firstName>
    <position>Data analyst</position>
    </employee>
    If this is the wrong, then what is the correct way to access the xml node based on an attribute?  How can i get that node 347 in this example to be found and returned?  I've opened a ticket with the adobe help team and we're on the 8th day and they have not been helpful at all.

    If you are using e4x as the result format for your service
    you can do the following
    //a XMLList of all day information
    var result:Object = event.result.day;
    //consits all information for month zero
    var month0:XMLList = result.(@month == 0);
    //consists of booking info for day 28 of month 0
    var day28Month0:XMLList = month0.(@day == 28);
    //this also can be done
    //contains booking info for all months for day 28
    var day28AllMonths:XMLList = result.(@day == 28);
    Using this technique you should be able to gather info about
    all user selected dates and build the smaller (filtered) list.
    HTH

Maybe you are looking for

  • Not sure i like the micro ph

    hello...first post. I just bought the micro photo on ebay. Looks cool, much heavier than my previous, but my first impression isn't great. I had the IAUDIO U2 and loved it! It was lost and while looking on ebay I got a deal for 00 bucks for the micro

  • I'm getting the apple and the loading sign

    I'm getting the apple and the loading sign I'm not sure what's wrong with my Mac book Pro just yesterday it was working fine and then I tried to shut it down it wasn't working it just freezed so I pushed the restart button and since then it's not wor

  • Can't get bluetooth to work on bootcamp

    I have macbook pro late 2008 model and i decided to install windows server 2008 r2 on it by using boot camp for my school work. I have used windows xp, 7 and 8 all under  the bootcamp without any problem but with windows server 2008 r2 i just can't g

  • Unable to login any user id first time in the Adobe content viewer (R25)

    Hi, I am using R25 Adobe content viewer. The problem is that I am unable to login any user id first time. when I do 2nd time with same id then it do successfully. Please suggest. DC Pub

  • Report Question - NAV attributes

    Can I create a variable if it is a displayed attribute?