Ned help parsing XML

I have an XML result that is coming back with aliases. I am
parsing this data and putting each element into a database. A
sample of the XML Structure is attached. I am using the ARRAYLEN
feature to count the child elements but that generates an error.
How can I get an accurate count of the <ALIAS> element in
this XML so I now how many times to loop through that set of
elements?
Thanks

if you use cfhttp to read the xml into a variable and then
CFDUMP it, you will be able to see all the variables that CF uses
in XML parsing, including the ones in your file and the ones you
need to access the nested variables.
This is code from an app I use to run through a list of games
played from Halo2 using Bungie's XML feed to CF.
This will likely give you a good starting point.

Similar Messages

  • Help parsing XML file

    Hi All,
    I have some troubles trying to load and parse a simple xml file like this:
    <?xml version="1.0" encoding="UTF-8"?>
    <entry>
         <id>1</id>
    </entry>
    <entry>
         <id>2</id>
    </entry>
    With this few lines of code:
                var url:URLRequest = new URLRequest("myXML.xml");
                var xml:XML;
                var rss:URLLoader = new URLLoader();
                rss.load(url);
                rss.addEventListener(Event.COMPLETE, readRss);
                function readRss(e:Event):void{
                    xml = XML(rss.data);               
                    var ns:Namespace=xml.namespace();
                    txt_field.text=xml..ns::entry[0].ns::id;           
    I get this error: A conflict exists with inherited definition spark.components:Application.url in namespace public.
    in: var url:URLRequest = new URLRequest("myXML.xml");
    Please help me ...  thank you in advance.
    Michele

    Hi Michele,
    Try to use different name for your URLRequest object...It seems that there is conflict existing with the inherited url property of the Application and the one you declared so do the following..
    var _url:URLRequest = new URLRequest("myXML.xml");
    var xml:XML;
    var rss:URLLoader = new URLLoader();
    rss.load(_url);
    Thanks,
    Bhasker

  • Please help parse XML

    First, the a sample XML to be parsed:
    <item name='HTMLContent_3'><richtext>
    <pardef id='1' leftmargin='1in' rightmargin='100%' tabs='L0.5000in L1in L1.5000in L2in L2.5000in L3in L3.5000in L4in'/>
    <par def='1'><p class="MsoBodyText">N.A.</p></par></richtext></item>This code is exported from a Lotus Domino database and represents a richtext field. I just want to export the text; in this case, that is the "N.A." and keep the line-breaks. Text formatting, bolding, etc. does not matter.
    Some <item> nodes are very long, with multiple <pardef> and <par def='1'> elements. Also, in my text editor greater than and less than symbols around the paragraph tag is listed as "<" and ">" (but I doubt that's a factor in the parsing).
    The <item> element is passed into the code sample below as Element e. I can get down to the <richtext> element with:
    Node child = e.getFirstChild();Then I can get the <pardef> and <par> nodes with:
    NodeList paragraphs = child.getChildNodes();But anything I try to get the text out of those nodes fails with a cast exception, prints out the XML, or doesn't do anything at all. Here is my current attempt:
    public static String getLongCharDataFromRichtext(Element e) {
         String answer = "";
         Node child = e.getFirstChild();     // Should be the <richtext> element.
         NodeList paragraphs = child.getChildNodes();
         for (int i=0; i<paragraphs.getLength(); i++) {
    //          String txt = paragraphs.item(i).toString();
    //          System.out.println(txt);
    //          answer += txt;
              Node paragraph = (Node)paragraphs.item(i);
              System.out.println(paragraph.toString());
    //          if (paragraph.getNodeType() == 3) {   // node type 3 is text node.
    //               String txt = paragraph.getNodeValue();
    //               String txt = getCharacterDataFromElement(paragraph);
    //               answer += txt;
         return answer;
    }I've been stumped on this for a while so I really, really appreciate your help!.
    -Jeff

    OK. I get what you're saying (including the hint that maybe this should have gone in the "New to Java" forum <G>). But now I'm having a second problem. The XML parser does not recognize the paragraph tags as an extra node on the tree.
    First, here is my current code:
    public static String getLongCharDataFromElement(Element e) {
         String answer = "";
         Node child = e.getFirstChild();     // Should be the <richtext> element.
         NodeList paragraphs = child.getChildNodes();
         for (int i=0; i<paragraphs.getLength(); i++) {
              Node paragraph = (Node)paragraphs.item(i);
              if (paragraph.getNodeName().equalsIgnoreCase("par")) {
                   Node theText = paragraph.getFirstChild();
                   String val = theText.getNodeValue();
                   System.out.println(val);
    }When I print out val, it prints the entire text of the paragraph tag (including the tag). I can't get a child node and I can't cast it to an Element or do anything.
    The XML parser I'm using is as follows:
    File file = new File("Answers.dxl");
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = builder.parse(file);Why won't the parser recognize the paragraph tags as a new Node?
    Thanks,
    -Jeff

  • Help Parsing XML Mesage using PeopleCode

    Hi all,
    I'm new to web services and XML but was able to consume a WSDL and call the web service successfully.
    I'm now trying to parse the XML message I’m getting as a response and to extract values i need and having issues Parsing the response. Below is what I have done and the code from my Test AE. Basically I’m trying to navigate to the "Results" element in the response and then use GetChildNode to get child nodes and then use FindNode to find elements and their values.
    Here is the WSLD I consumed to create the web service in PS. I only need WSDL operation doSearch_3_15
    [https://www.epls.gov/epls/services/EPLSSearchWebService?wsdl ]
    My PC below calls the web service and passes last name “ZERMENO” as a search parameter and this should return 3 results back.
    I’m grabbing the reply back and parse it to extract the values I need.
    +&inXMLDoc = CreateXmlDoc("");+
    +&ret = &inXMLDoc.ParseXmlString(&reply.GenXMLString());+
    The issue I’m having is being able to get “inside” the results node (there are 3 of them) and loop through the child nodes and get my values.
    Code from Test AE:
    Local string &payload, &responseStr, &last;
    Local Message &msg, &reply;
    Local XmlDoc &xml, &inXMLDoc;
    Local array of XmlNode &GetElements, &RecordList, &field1List, &aResultsNode;
    Local XmlNode &RecordNode, &ClassificationNode;
    Local File &MYFILE;
    +&FilePath = "/psoft/fin9/fpsdv1/prod/ap/files/";+
    +&FileName = "uhc_report.xml";+
    +&MYFILE = GetFile(&FilePath | &FileName, "W", %FilePath_Absolute);+
    +&payload = "<?xml version='1.0'?> <doSearch xmlns='https://www.epls.gov/epls/services/EPLSSearchWebService'>";+
    +&first = "";+
    +&last = "ZERMENO";+
    +&payload = &payload | "<query><first>" | &first | "</first><last>" | &last | "</last></query> </doSearch>";+
    +&xml = CreateXmlDoc(&payload);+
    +&msg = CreateMessage(Operation.DOSEARCH_3_15, %IntBroker_Request);+
    +&msg.SetXmlDoc(&xml);+
    +&reply = %IntBroker.SyncRequest(&msg);+
    If All(&reply) Then
    If &MYFILE.IsOpen Then
    +&MYFILE.WriteString(&reply.GenXMLString());+
    Else
    MessageBox(0, "", 0, 0, "Can't Open File.");
    End-If;
    +&inXMLDoc = CreateXmlDoc("");+
    +&ret = &inXMLDoc.ParseXmlString(&reply.GenXMLString());+
    If &ret Then
    +&field1List = &inXMLDoc.GetElementsByTagName("results");+
    If &field1List.Len = 0 Then
    MessageBox(0, "", 0, 0, "GetElementsByTagName Node not found");
    Error ("GetElementsByTagName Node not found");
    +/* do error processing */+
    Else
    For &j = 1 To &field1List.Len
    If &j > 1 Then
    +MessageBox(0, "", 0, 0, &field1List [&j].NodeName | " = " | &field1List [&j].NodeValue);+
    +&RecordNode = &inXMLDoc.DocumentElement.GetChildNode(&j);+
    If &RecordNode.IsNull Then
    MessageBox(0, "", 0, 0, "GetChildNode not found");
    Else
    +&ClassificationNode = &RecordNode.FindNode("classification");+
    If &ClassificationNode.IsNull Then
    MessageBox(0, "", 0, 0, "FindNode not found");
    Else
    +&SDN_TYPE = Substring(&ClassificationNode.NodeValue, 1, 50);+
    MessageBox(0, "", 0, 0, "&SDN_TYPE = " | &SDN_TYPE);
    End-If;
    End-If;
    End-If;
    End-For;
    End-If;
    MessageBox(0, "", 0, 0, &inXMLDoc.DocumentElement.NodeName);
    Else
    +/* do error processing */+
    MessageBox(0, "", 0, 0, "Error. ParseXml");
    End-If;
    Else
    MessageBox(0, "", 0, 0, "Error. No reply");
    End-If;
    see link below for the XML reply web service message with some Notes. Also link for the response as an XML doc (had to add .txt to the xml extension to be able to upload it).  I appreciate your help and feedback.
    http://compshack.com/files/XML-Message.png
    http://compshack.com/files/uhc_report.xml_.txt
    And here is the output from my Test AE. I'm able to find 3 count of results, which i expected since I have 3 records coming back from the web service, but for what ever reason, GetChildNode is failing.
    results = (0,0)
    GetChildNode not found (0,0)
    results = (0,0)
    GetChildNode not found (0,0)
    results = (0,0)
    GetChildNode not found (0,0)
    Edited by: Maher on Mar 12, 2012 10:21 AM
    Edited by: Maher on Mar 12, 2012 10:41 AM

    Hi,
    I just took a closer look at the code and the looping using childnodes and findnode is not correct a bit overkill.
    You should really use the one or the other.
    I have created two other loops
    Loop 1, loop through all elements using Childnodes:
    Local string &payload, &responseStr, &last;
    Local Message &msg, &reply;
    Local XmlDoc &xml, &inXMLDoc;
    Local array of XmlNode &GetElements, &RecordList, &field1List, &aResultsNode;
    Local XmlNode &RecordNode, &ClassificationNode;
    Local File &MYFILE;
    &inXMLDoc = CreateXmlDoc("");
    &ret = &inXMLDoc.ParseXmlFromURL("c:\temp\test.xml");
    If &ret Then
       &field1List = &inXMLDoc.GetElementsByTagName("results");
       If &field1List.Len = 0 Then
          MessageBox(0, "", 0, 0, "GetElementsByTagName Node NOT found");
          Error ("GetElementsByTagName Node NOT found"); /* do error processing */
       Else
          For &j = 1 To &field1List.Len
             If &j > 1 Then
                MessageBox(0, "", 0, 0, &field1List [&j].NodeName | " = " | &field1List [&j].NodeValue);
                &RecordNode = &field1List [&j];
                &RecordChildNode = &RecordNode.GetChildNode(&j);
                If &RecordChildNode.IsNull Then
                   MessageBox(0, "", 0, 0, "GetChildNode NOT found");
                Else
                   MessageBox(0, "", 0, 0, "&RecordChildNode name:" | &RecordChildNode.NodeName);
                   If &RecordChildNode.NodeName = "classification" Then
                      MessageBox(0, "", 0, 0, "NodeName = " | &RecordChildNode.NodeName);
                      &SDN_TYPE = Substring(&RecordChildNode.NodeValue, 1, 50);
                      MessageBox(0, "", 0, 0, "&SDN_TYPE = " | &SDN_TYPE);
                   End-If;
                End-If;
             End-If;
          End-For;
       End-If;
       MessageBox(0, "", 0, 0, &inXMLDoc.DocumentElement.NodeName);
    Else /* do error processing */
       MessageBox(0, "", 0, 0, "Error. ParseXml");
    End-If;results = (0,0)
    Message Set Number: 0
    Message Number: 0
    Message Reason: results = (0,0) (0,0)
    &RecordChildNode name:address (0,0)
    Message Set Number: 0
    Message Number: 0
    Message Reason: &RecordChildNode name:address (0,0) (0,0)
    results = (0,0)
    Message Set Number: 0
    Message Number: 0
    Message Reason: results = (0,0) (0,0)
    &RecordChildNode name:agencyUID (0,0)
    Message Set Number: 0
    Message Number: 0
    Message Reason: &RecordChildNode name:agencyUID (0,0) (0,0)
    results = (0,0)
    Message Set Number: 0
    Message Number: 0
    Message Reason: results = (0,0) (0,0)
    &RecordChildNode name:classification (0,0)
    Message Set Number: 0
    Message Number: 0
    Message Reason: &RecordChildNode name:classification (0,0) (0,0)
    NodeName = classification (0,0)
    Message Set Number: 0
    Message Number: 0
    Message Reason: NodeName = classification (0,0) (0,0)
    &SDN_TYPE =
    Individual (0,0)
    Message Set Number: 0
    Message Number: 0
    Message Reason: &SDN_TYPE =
    Individual (0,0) (0,0)
    soapenv:Envelope (0,0)
    Message Set Number: 0
    Message Number: 0
    Message Reason: soapenv:Envelope (0,0) (0,0)
    Loop 2, look for classification node, using FindNode:
    Local string &payload, &responseStr, &last;
    Local Message &msg, &reply;
    Local XmlDoc &xml, &inXMLDoc;
    Local array of XmlNode &GetElements, &RecordList, &field1List, &aResultsNode;
    Local XmlNode &RecordNode, &ClassificationNode;
    Local File &MYFILE;
    &inXMLDoc = CreateXmlDoc("");
    &ret = &inXMLDoc.ParseXmlFromURL("c:\temp\test.xml");
    If &ret Then
       &field1List = &inXMLDoc.GetElementsByTagName("results");
       If &field1List.Len = 0 Then
          MessageBox(0, "", 0, 0, "GetElementsByTagName Node NOT found");
          Error ("GetElementsByTagName Node NOT found"); /* do error processing */
       Else
          For &j = 1 To &field1List.Len
             If &j > 1 Then
                &RecordNode = &field1List [&j];
                &ClassificationNode = &RecordNode.FindNode("classification");
                If &ClassificationNode.IsNull Then
                   MessageBox(0, "", 0, 0, "FindNode not found");
                Else
                   &SDN_TYPE = Substring(&ClassificationNode.NodeValue, 1, 50);
                   MessageBox(0, "", 0, 0, "&SDN_TYPE = " | &SDN_TYPE);
                End-If;
             End-If;
          End-For;
       End-If;
       MessageBox(0, "", 0, 0, &inXMLDoc.DocumentElement.NodeName);
    Else /* do error processing */
       MessageBox(0, "", 0, 0, "Error. ParseXml");
    End-If;&SDN_TYPE =
    Individual (0,0)
    Message Set Number: 0
    Message Number: 0
    Message Reason: &SDN_TYPE =
    Individual (0,0) (0,0)
    &SDN_TYPE =
    Individual (0,0)
    Message Set Number: 0
    Message Number: 0
    Message Reason: &SDN_TYPE =
    Individual (0,0) (0,0)
    &SDN_TYPE =
    Individual (0,0)
    Message Set Number: 0
    Message Number: 0
    Message Reason: &SDN_TYPE =
    Individual (0,0) (0,0)
    soapenv:Envelope (0,0)
    Message Set Number: 0
    Message Number: 0
    Message Reason: soapenv:Envelope (0,0) (0,0)
    As you can see, several possible solutions are possible.
    Hope this helps.
    Hakan

  • Ned help on JSP parsing XML

    Hi all.
    Im having problems on how to parse an xml by JSP
    Can anyone teach me how to parse an the XML below by jsp, without using taglibs. Im using JDOM...
    <Customer>
               <DetailsCustomer ID = 1>
               <Name>
                      John
               </Name>
               <DetailsCustomer ID = 2>
               <Name>
                     Michael
               </Name>
    <Customer>Thankz :)
    Hope for a kind reply :)

    Hi,
    Why would you like to parse the XML inside a JSP page? JSP are for rendering and not for parsing XML. The code to parse the XML should be put in an ordinary Java class instead.
    Parsing XML can be done in a number of ways...it all depends on what you want to do with the XML. Are you looking for XML -> Java Object then maybe you should look at XStream or JAXB.
    If you can tell me a little more about your use case maybe I can help you a little bit more.
    /klejs

  • How to parse XML to Java object... please help really stuck

    Thank you for reading this email...
    If I have a **DTD** like:
    <!ELEMENT person (name, age)>
    <!ATTLIST person
         id ID #REQUIRED
    >
    <!ELEMENT name ((family, given) | (given, family))>
    <!ELEMENT age (#PCDATA)>
    <!ELEMENT family (#PCDATA)>
    <!ELEMENT given (#PCDATA)>
    the **XML** like:
    <person id="a1">
    <name>
         <family> Yoshi </family>
         <given> Samurai </given>
    </name>
    <age> 21 </age>
    </person>
    **** Could you help me to write a simple parser to parse my DTD and XML to Java object, and how can I use those objects... sorry if the problem is too basic, I am a beginner and very stuck... I am very confuse with SAXParserFactory, SAXParser, ParserAdapter and DOM has its own Factory and Parser, so confuse...
    Thank you for your help, Yo

    Hi, Yo,
    Thank you very much for your help. And I Wish you are there...I'm. And I plan to stay - It's sunny and warm here in Honolulu and the waves are up :)
    A bit more question for dear people:
    In the notes, it's mainly focus on JAXB,
    1. Is that mean JAXB is most popular parser for
    parsing XML into Java object? With me, definitely. There are essentially 3 technologies that allow you to parse XML documents:
    1) "Callbacks" (e.g. SAX in JAXP): You write a class that overrides 3 methods that will be called i) whenever the parser encounters a start tag, ii) an end tag, or iii) PCDATA. Drawback: You have to figure out where the heck in the document hierarchy you are when such a callback happens, because the same method is called on EACH start tag and similarly for the end tag and the PCDATA. You have to create the objects and put them into your own data structure - it's very tedious, but you have complete control. (Well, more or less.)
    2) "Tree" (e.g. DOM in JAXP, or it's better cousin JDOM): You call a parser that in one swoop creates an entire hierarchy that corresponds to the XML document. You don't get called on each tag as with SAX, you just get the root of the resulting tree. Drawback: All the nodes in the tree have the same type! You probably want to know which tags are in the document, don't you? Well, you'll have to traverse the tree and ask each node: What tag do you represent? And what are your attributes? (You get only strings in response even though your attributes often represent numbers.) Unless you want to display the tree - that's a nice application, you can do it as a tree model for JTree -, or otherwise don't care about the individual tags, DOM is not of much help, because you have to keep track where in the tree you are while you traverse it.
    3) Enter JAXB (or Castor, or ...): You give it a grammar of the XML documents you want to parse, or "unmarshall" as the fashion dictates to call it. (Actually the name isn't that bad, because "parsing" focuses on the input text while "unmarshalling" focuses on the objects you get, even though I'd reason that it should be marshalling that converts into objects and unmarshalling that converts objects to something else, and not vice versa but that's just my opinion.) The JAXB compiler creates a bunch of source files each with one (or now more) class(es) (and now interfaces) that correspond to the elements/tags of your grammar. (Now "compiler" is a true jevel of a misnomer, try to explain to students that after they run the "compiler", they still need to compile the sources the "compiler" generated with the real Java compiler!). Ok, you've got these sources compiled. Now you call one single method, unmarshall() and as a result you get the root node of the hierarchy that corresponds to the XML document. Sounds like DOM, but it's much better - the objects in the resulting tree don't have all the same type, but their type depends on the tag they represent. E.g if there is the tag <ball-game> then there will be an object of type myPackage.BallGame in your data structure. It gets better, if there is <score> inside <ball-game> and you have an object ballGame (of type BallGame) that you can simply call ballGame.getScore() and you get an object of type myPackage.Score. In other words, the child tags become properties of the parent object. Even better, the attributes become properties, too, so as far as your program is concerned there is no difference whether the property value was originally a tag or an attribute. On top of that, you can tell in your schema that the property has an int value - or another primitive type (that's like that in 1.0, in the early release you'll have to do it in the additional xjs file). So this is a very natural way to explore the data structure of the XML document. Of course there are drawbacks, but they are minor: daunting complexity and, as a consequence, very steep learning curve, documentation that leaves much to reader's phantasy - read trial and error - (the user's guide is too simplicistic and the examples too primitive, e.g. they don't even tell you how to make a schema where a tag has only attributes) and reference manual that has ~200 pages full of technicalities and you have to look with magnifying glas for the really usefull stuff, huge number of generated classes, some of which you may not need at all (and in 1.0 the number has doubled because each class has an accompanying interface), etc., etc. But overall, all that pales compared to the drastically improved efficiency of the programmer's efforts, i.e. your time. The time you'll spend learning the intricacies is well spent, you'll learn it once and then it will shorten your programming time all the time you use it. It's like C and Java, Java is order of magnitude more complex, but you'd probably never be sorry you gave up C.
    Of course the above essay leaves out lots and lots of detail, but I think that it touches the most important points.
    A word about JAXB 1.0 vs. Early Release (EA) version. If you have time, definitively learn 1.0, they are quite different and the main advantage is that the schema combines all the info that you had to formulate in the DTD and in the xjs file when using the EA version. I suggested EA was because you had a DTD already, but in retrospect, you better start from scratch with 1.0. The concepts in 1.0 are here to stay and once your surmounted the learning curve, you'll be glad that you don't have to switch concepts.
    When parser job is done,
    what kind of Java Object we will get? (String,
    InputStream or ...)See above, typically it's an object whose type is defined as a class (and interface in 1.0) within the sources that JABX generates. Or it can be a String or one of the primitive types - you tell the "compiler" in the schema (xjs file in EA) what you want!
    2. If we want to use JAXB, we have to contain a
    XJS-file? Something like:In EA, yes. In 1.0 no - it's all in the schema.
    I am very new to XML, is there any simpler way to get
    around them? It has already take me 4 days to find a
    simple parser which give it XML and DTD, then return
    to me Java objects ... I mean if that kind of parser
    exists....It'll take you probably magnitude longer that that to get really familiar with JAXB, but believe me it's worth it. You'll save countless days if not weeks once you'll start developing serious software with it. How long did it take you to learn Java and it's main APIs? You'll either invest the time learning how to use the software others have written, or you invest it writing it yourself. I'll take the former any time. But it's only my opinion...
    Jan

  • Help : Parsing large XML files

    Hi,
    someone please help, I am trying to parse XML files of about 60 MB, I have to parse throught 120 of them , search for a particular node and print it. I am using jdk1.3.x , using jdom
    On the sample filesd that r available of 114KB i am able to run my code and get the result, but as soon as the large files are used I get the following error
    OutOfMemoryError
    <<nostacktrace>>
    Exception in thread main
    thanks

    I guess you are using a DOM parser which builds a complete tree of the document. For what you are trying to do this is probably not necessary so a SAX parser may be better. If JDOM doesn't have one try using Xerces from Apache.

  • Need help on parsing xml file...

    Hi all,
    I need to collect some data from an Xml file using java. I have the following code with me but I am unable to get the required result. I am unable to get the data from the tags belonging to the header and footer elements. Please find the code and the sample xml file below.
    Program to parse XML:
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    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.NodeList;
    import org.xml.sax.SAXException;
    public class JobLogDetails3{
         //No generics
         List myJobs;
         Document dom;
         public JobLogDetails3(){
              //create a list to hold the job objects
              myJobs = new ArrayList();
         public void runJobDetails() {
              //parse the xml file and get the dom object
              parseXmlFile();
              //get each joblog element and create a job object
              parseDocument();
              //Iterate through the list and print the data
              printData();
         private void parseXmlFile(){
              //get the factory
              DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
              try {
                   //Using factory get an instance of document builder
                   DocumentBuilder db = dbf.newDocumentBuilder();
                   //parse using builder to get DOM representation of the XML file
                   dom = db.parse("test.xml");
              }catch(ParserConfigurationException pce) {
                   pce.printStackTrace();
              }catch(SAXException se) {
                   se.printStackTrace();
              }catch(IOException ioe) {
                   ioe.printStackTrace();
         private void parseDocument(){
              //get the root elememt
              Element docEle = dom.getDocumentElement();
              //get a nodelist of <joblog> elements
              NodeList nl = dom.getElementsByTagName("*");
              if(nl != null && nl.getLength() > 0) {
                   for(int i = 0 ; i < nl.getLength();i++) {
                        //get the joblog element
                        Element el = (Element)nl.item(i);
                        //get the joblog object
                        Job J = getJob(el);
                        //add it to list
                        myJobs.add(J);
         * I take an joblog element and read the values in, create
         * an joblog object and return it
         * @param JobEl
         * @return
         private Job getJob(Element JobEl) {
              //for each <joblog> element get text or int values of
              //name ,id, age and name
              String jobServer = getTextValue(JobEl,"server");
              String jobName = getTextValue(JobEl,"name");
              String jobClient = getTextValue(JobEl,"machine_name");
              String jobStart = getTextValue(JobEl,"start_time");
              String jobType = getTextValue(JobEl,"type");
              String jobEnd = getTextValue(JobEl,"end_time");
              String jobSize = getTextValue(JobEl,"new_processed_bytes");
              //Create a new Job with the value read from the xml nodes
              Job J = new Job(jobServer,jobName,jobClient,jobStart,jobType,jobEnd,jobSize);
              return J;
         * I take a xml element and the tag name, look for the tag and get
         * the text content
         * i.e for <employee><name>John</name></employee> xml snippet if
         * the Element points to employee node and tagName is name I will return John
         * @param ele
         * @param tagName
         * @return
         private String getTextValue(Element ele, String tagName) {
              String textVal = null;
              NodeList nl = ele.getElementsByTagName(tagName);
              if(nl != null && nl.getLength() > 0) {
                   Element el = (Element)nl.item(0);
                   textVal = el.getFirstChild().getNodeValue();
              return textVal;
         * Calls getTextValue and returns a int value
         * @param ele
         * @param tagName
         * @return
         private int getIntValue(Element ele, String tagName) {
              //in production application you would catch the exception
              return Integer.parseInt(getTextValue(ele,tagName));
         * Iterate through the list and print the
         * content to console
         private void printData(){
              System.out.println("No of Jobs '" + myJobs.size() + "'.");
              Iterator it = myJobs.iterator();
              while(it.hasNext()) {
                   System.out.println(it.next().toString());
         public static void main(String[] args){
              //create an instance
              JobLogDetails JLD = new JobLogDetails();
              //call run example
              JLD.runJobDetails();
    Job Class
    public class Job {
         private String jobServer;
    private String jobName;
    private String jobClient;
    private String jobStart;
    private String jobType;
    private String jobEnd;
    private String jobSize;
         public Job(){
         public Job(String jobServer,String jobName,String jobClient,String jobStart,String jobType,String jobEnd,String jobSize ) {
              this.jobServer = jobServer;
              this.jobName = jobName;
              this.jobClient = jobClient;
    this.jobStart = jobStart;
              this.jobType = jobType;
    this.jobEnd = jobEnd;
    this.jobSize = jobSize;
         public String getjobServer() {
              return jobServer;
         public void setjobServer(String jobServer) {
              this.jobServer = jobServer;
         public String getjobName() {
              return jobName;
         public void setjobname(String jobName) {
              this.jobName = jobName;
         public String getjobClient() {
              return jobClient;
         public void setjobClient(String jobClient) {
              this.jobClient = jobClient;
    public String getjobStart() {
              return jobStart;
         public void setjobStart(String jobStart) {
              this.jobStart = jobStart;
    public String getjobType() {
              return jobType;
         public void setjobType(String jobType) {
              this.jobType = jobType;
    public String getjobEnd() {
              return jobEnd;
         public void setjobEnd(String jobEnd) {
              this.jobEnd = jobEnd;
    public String getjobSize() {
              return jobSize;
         public void setjobSize(String jobSize) {
              this.jobSize = jobSize;
         public String toString() {
              StringBuffer sb = new StringBuffer();
    sb.append(getjobServer());
              sb.append(",");
    sb.append(getjobName());
              sb.append(",");
              sb.append(getjobClient());
              sb.append(",");
              sb.append(getjobType());
              sb.append(",");
              sb.append(getjobStart());
              sb.append(",");
              sb.append(getjobEnd());
              sb.append(",");
              sb.append(getjobSize());
              sb.append(",");
              return sb.toString();
    Sample XML File:
    <?xml version="1.0" encoding="UTF-16" ?>
    - <joblog>
    <job_log_version version="2.0" />
    - <header>
    <filler>======================================================================</filler>
    <server>Job server: TGBBAK</server>
    <name>Job name: TGBSAP4-SQL-SQL DB Servers S2T - High-Weekly Full Backup</name>
    <start_time>Job started: 26 September 2011 at 01:00:04</start_time>
    <type>Job type: Backup</type>
    <log_name>Job Log: GFD_TGBBAK_71887.xml</log_name>
    <filler>======================================================================</filler>
    </header>
    <media_mount_date>Drive and media mount requested: 26/09/2011 01:00:04</media_mount_date>
    - <media_drive_and_media_info>
    <media_mount_date>Drive and media information from media mount: 26/09/2011 01:00:39</media_mount_date>
    <robotic_library_name>Robotic Library Name: HP 1</robotic_library_name>
    <drive_name>Drive Name: LTO4_2</drive_name>
    <slot>Slot: 43</slot>
    <media_label>Media Label: 000059L</media_label>
    <media_guid>Media GUID: {a6ca0062-7a6f-4b4b-8144-732ca25f2f9d}</media_guid>
    <media_overwrite_date>Overwrite Protected Until: 25/10/2011 19:24:58</media_overwrite_date>
    <media_append_date>Appendable Until: 02/10/2011 14:00:30</media_append_date>
    <media_set_target>Targeted Media Set Name: Weekly Tape</media_set_target>
    </media_drive_and_media_info>
    - <backup>
    <filler>======================================================================</filler>
    <title>Job Operation - Backup</title>
    <append_or_overwrite>Media operation - append.</append_or_overwrite>
    <compression>Compression Type: Hardware [if available, otherwise none]</compression>
    <verify_option>WARNING: The option 'Verify after backup completes' was not selected. Performing a verify operation to make sure that media can be read after the backup has completed is recommended.</verify_option>
    <filler>======================================================================</filler>
    - <machine>
    <machine_name>TGBSAP4.Tetley.Grp</machine_name>
    <info>Network control connection is established between 10.22.2.18:3271 <--> 10.22.2.4:10000</info>
    <info>Network data connection is established between 10.22.2.18:3301 <--> 10.22.2.4:3094</info>
    - <set>
    <set_resource_name>TGBSAP4.Tetley.Grp</set_resource_name>
    <tape_name>Family Name: "Media created 25/09/2011 13:59:55"</tape_name>
    - <volume>
    <display_volume>Backup of "TGBSAP4.Tetley.Grp "</display_volume>
    </volume>
    <description>Backup set #45 on storage media #1 Backup set description: "Weekly Full Backup"</description>
    <backup_type>Backup Method: Full - Back up entire database or filegroup</backup_type>
    <agent_started>Microsoft SQL Server Agent: Started</agent_started>
    <start_time>Backup started on 26/09/2011 at 01:01:45.</start_time>
    - <database>
    <database>Database PRD</database>
    </database>
    - <database>
    <database>Database master</database>
    </database>
    - <database>
    <database>Database model</database>
    </database>
    - <database>
    <database>Database msdb</database>
    </database>
    <end_time>Backup completed on 26/09/2011 at 02:42:25.</end_time>
    - <summary>
    <backed_up_database>Backed up 4 databases</backed_up_database>
    <new_processed_bytes>Processed 573363576542 bytes in 1 hour, 40 minutes, and 40 seconds.</new_processed_bytes>
    <vlm_hist_rateformat2>Throughput rate: 5432 MB/min</vlm_hist_rateformat2>
    </summary>
    <filler>----------------------------------------------------------------------</filler>
    </set>
    </machine>
    </backup>
    - <footer>
    <filler>======================================================================</filler>
    <end_time>Job ended: 26 September 2011 at 02:43:12</end_time>
    <engine_completion_status>Job completion status: Successful</engine_completion_status>
    <filler>======================================================================</filler>
    <completeStatus>19</completeStatus>
    </footer>
    </joblog>

    1. your code does not compile (in your main method you try to create an instance of a class which does not exist).
    2. your XML document is not well formed.
    +[Fatal Error] test.xml:34:74: The content of elements must consist of well-formed character data or markup.+
    org.xml.sax.SAXParseException: The content of elements must consist of well-formed character data or markup.
    Maybe there are other problems but you can start by fixing these.

  • Parsing XML data stored as CLOB in DB and save attribute values in table

    Hello,
    I have a CLOB column in table that is holding XML data as follows,
    <banners>
    <banner-image id="0">
    <type>BANNER</type>
    <local-path>http.gif</local-path>
    <click-through-url>www</click-through-url>
    <make>Acura</make>
    </banner-image>
    <banner-image id="1">
    <type>BANNER</type>
    <local-path>http.gif</local-path>
    <click-through-url>gfrty</click-through-url>
    <make>BMW</make>
    </banner-image>
    </banners>
    Now I need to parse thru the above XML data and pull the attribute values to store in another table as follows,
    BANNER_IMAGE_ID | TYPE | LOCAL_PATH | CLICK_URL | MAKE
    0 | BANNER | http.gif | www | Acura
    1 | BANNER | http.gif | gfrty | BMW
    And XML data doesn't always end up with 2 rows in this table....some times it may be 3 or 4 as well. It is just that in this example it ended up with 2 rows.
    So, I would appreciate if someone can help me find a generic way of doing this,
    Thank you in advance,
    Madhu.

    This is not a reply.. sorry.
    I took have a similar problem only..
    can you pls help me
    XML structure.
    <PODetails>
    <POHeader>
    <CurrencyID>INR</CurrencyID>
    <ExchangeRate>1</ExchangeRate>
    <RefNo>0080000110</RefNo>
    <VendorID>1200</VendorID>
    <TransDate>2006-12-20</TransDate>
    <DocRelationshipId>PURCHASE</DocRelationshipId>
    <LocationID>0000102327</LocationID>
    </POHeader>
    <POItemDetails>
    <ItemID>ARSH1332</ItemID>
    <Size>L HS</Size>
    <Quality>Q1</Quality>
    <CustPO>rush order</CustPO>
    <UOM>PC</UOM>
    <Quantity>3.000</Quantity>
    <PriceValue>2509.5</PriceValue>
    <TaxAmount>0.00</TaxAmount>
    </POItemDetails>
    <POItemDetails>
    <ItemID>ARSH1332</ItemID>
    <Size>M HS</Size>
    <Quality>Q1</Quality>
    <CustPO>rush order</CustPO>
    <UOM>PC</UOM>
    <Quantity>2.000</Quantity>
    <PriceValue>1673</PriceValue>
    <TaxAmount>0.00</TaxAmount>
    </POItemDetails>
    <POItemDetails>
    <ItemID>ARSH1556</ItemID>
    <Size>39FS</Size>
    <Quality>Q1</Quality>
    <CustPO>rush order</CustPO>
    <UOM>PC</UOM>
    <Quantity>1.000</Quantity>
    <PriceValue>836.5</PriceValue>
    <TaxAmount>0.00</TaxAmount>
    </POItemDetails>
    </PODetails>
    The DB is ORACLE 9i
    This is stored in a XML table of type XMLTYPE.
    THIS I USED THE .extract function to get the values of the nodes.
    POHeader details are working fine. But when i get the POItemDetails i am getting 'ARSH1332ARSH1332ARSH1556' when i issue the command
    select a.extract('/PODetails/POItemDetails/ItemID/text()').getStringVal() ItemID
    FROM xmltable a
    WHERE a.existsnode('//POItemDetails/ItemID')=1
    Pls Help..
    Regds,
    Santhoshkumar.G.

  • LO Error 26005 Failed to parse XML

    Good Afternoon,
    I currently have an Xcelsius document that is attached to a Crystal Report that is in Infoview.  I have it connected by using Live Office.  The Crystal report basically contains a cross tab of data and is run nightly in our system.  I bring back the data into Excel in order to build an Xcelsius document off of it.  I havent' been using the Live Office piece all that much until recently therefore please excuse my ignorance.  I setup my data connection as a Live Office connection.  My server connection seems to be correct:
    http://WHGCRYSTAL3:8080/dswsbobje/services/session
    However, when I try to refresh the document, I get the following error:
    soapenv:Server.generalException: Failed to parse XML. (LO 26005)
    Any ideas as to what this could be?  I have Crystal Xcelsius Enterprise 2008.  The version is 5.0.0.99 and the build number is 12,0,0,121.  I think I am all updated on service packs but I could  be wrong.  Any help is appreciated.

    I downloaded all of the service packs and fixes and now I am up to date.  I am still getting the error with an additional error.   This is what is says:
    Failed to parse XML. (LO 26005) (LO 26000)
    Any other ideas as to why this is happening?

  • Parse XML in a java stored proc

    I am trying to parse an xml document in a java stored procedure. Just following my nose, I have developed a stored proc that works fine in development (outside the database using JRE 1.4.1) using the Xerces 2.5 parser. But, after having transferred the xerces xercesImpl.jar, xmlapis.jar, and my implementation class into oracle using loadjava when I call my stored proc the code throws an exception trying to build the document with an error like:
    NoClassDef exception org.apache.xerces.jaxp.DocumentFactoryBuilderImpl
    My Code looks like this:
    import java.io.IOException;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.FactoryConfigurationError;
    import javax.xml.parsers.ParserConfigurationException;
    import org.w3c.dom.Document;
    import org.xml.sax.SAXException;
    InputStream is = getXMLAsInputStream(xml);
    try {
    DocumentBuilderFactory factory =
    DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse( is );
    ... parse the document ....
    catch (FactoryConfigurationError e) {
    // unable to get a document builder factory
    The exception caught is a FactoryConfigurtionError.
    I'm not particularly attached to xerces, I'm really just looking for a way to parse XML inside my java stored proc, so any help to solve my problem, or an alternative suggestion will be greatly appreciated.
    thanks
    Dale

    I looked again and sure enough the xerces implementation classes were missing. I had run a .cmd file containing these two lines, but it looks like only the first one ran...
    loadjava -u ncc/xyz@usd -v -r M:\Database\JavaGeocode\Xerces2_5_0\xml-apis.jar
    loadjava -u ncc/xyz@usd -v -r M:\Database\JavaGeocode\Xerces2_5_0\xercesImpl.jar
    Now I've got everything working fine with Xerces!
    Dale

  • How do you store parsed XML data in an array

    Hi, i am trying to complete a small program which implements the SAX parser to parse an XML file. My problem is that i am writing a custom class to store the parsed data into an array, and then make the array available to the main program via a simple method which returns the array. I know this must be very simple to do, but i seem to have developed a mental block with this part of the program. I can parse the data and print all the elements to the screen, but i just cant figure out how to store all the data elements into the array. I will post the class which is supposed to do this, and ask anyone out there if they know what i'm doing wrong, and also, if there is a more effeicient way of achieving this ( i expect there definitely is!! but i have never used the SAX parser before and am getting confused by the API docs on it!!) Any help very much appreciated.
    Here is my attempt at coding the class to handle the parsed XML data
    class Sink extends org.xml.sax.helpers.DefaultHandler
         implements org.xml.sax.ContentHandler{
    Customer[] customers = new Customer[20];
         int count = 1;
         int x = 0;
         int tagCount = 0;
         String name;
    String custID;
         String username;
         String address;
         String phoneNum;
    public void startElement(String uri, String localName, String rawName, final org.xml.sax.Attributes attributes)throws org.xml.sax.SAXException{
    //count the number of <name> tags in the XML file
         if(rawName.equals("name")){
              tagCount++;
    public void characters(char[] ch, int start, int len){
    //get the current string
         String text = new String(ch, start, len);
         String text1 = text.trim();
    //there are 5 elements for each customer found in the XML file so when the count reaches 6
    // i reset this to 1
         if(count == 6){
         count = count - 5;
         if(text1.length()>0 && count == 1){
              name = text1;
              System.out.println(name);
              }else{
         if(text1.length()>0 && count == 2){
              custID = text1;
              System.out.println(custID);
                   }else{
                   if(text1.length()>0 && count == 3){
                   username = text1;
                   System.out.println(username);
                   }else{
                        if(text1.length()>0 && count == 4){
                        address = text1;
                        System.out.println(address);
                        }else{
                        if(text1.length()>0 && count == 5){
                             phoneNum = text1;
                             System.out.println(phoneNum);
                             //add data to the customer array
                             customers[x] = new Customer(name, custID, username, address, phoneNum);
    // increment the array index counter
                        x = x+1;
                        }//end of if
                        }//end else
                        }//end else
                   }//end else
              }//end else
    }//end of characters method
    public void endDocument(){
         System.out.println("There are " + tagCount +
         " <name> elements.");
    }//end of class Sink
    Before the end of this class i also need to make the array available to the calling program!!
    Any help would be much appreciated
    Thanks
    Iain

    Ok, yer going about this all the wrong way. You shouldn't have to maintain a count of all the elements. Basically you are locking yourself into the XML tags not only all being there but are assuming they are all in the same order. What you should do is in your characters() method, put all of the characters into a string buffer. Then, in endElement() (which you dont use btw, you should) you grab the information that is in the string buffer and store it into your Customer object depending on what the tagName is.
    Also, you should probably use a List to store all the Customer objects and not an single array, it's more dynamic and you arent locked into a set number of Customers.
    I wont do it all for you, but I'll give you a good outline to use.
    public class CustomerHandler extends DefaultHandler {
        private java.util.List customerList;  // List of Customer objects
        private java.util.StringBuffer buf;   // StringBuffer to store the string of characters between the start and end tags
        private Customer customer;  // Customer object that is initialized with each entry.
        public CustomerHandler() {
            customerList = new java.util.ArrayList();   // Initialize the List
            buf = new java.util.StringBuffer();   // Initialize the string buffer
        //  Make your customer list available to other classes
        public java.util.List getCustomerList() {
            return customerList;
        public void startElement(String nsURI, String sName, String tagName, Attributes attributes) throws SAXException {
            // Clear the String Buffer
            //  If the tagName is "Customer" then create a new Customer object
        public void characters(char[] ch, int start, int length) {
            //  append the characters into the string buffer
        public void endElement(String nsURI, String sName, String tagName) throws SAXException {
            // If the tagName is "Customer" add your customer object to the List
            // Place the data from the String Buffer into a String
            //  Depending on the tagName, call the appropriate set method on your customer object
    }

  • Java stored proc performance parsing XML docs

    Hi
    We are using ORACLE 8i(8.1.6). I have a JAVA Stored procedure that parses XML doc and returns tha values. If I am testing on the box, I get an avg. return time of 2 secs. If I have 20 users, my return time for all went to 25 to 35 secs?
    Are there any parameters on ORACLE I can modify to increase the performance. We are developing app for 1000 to 1500 users. I dont want to guess the time based on my test with 20 users.
    Any help will be greatly appreciated.
    Thank You
    Raju

    Raju,
    Oracle 8.1.7 should be better choice for you since it does have the XML stuff
    natively compiled.
    Regarding scaleability the JVM should scale
    very well. However let us know what you find.
    - Stefan

  • Parsing XML from a session bean

    Hi,
    I am trying to use a Sax parser for parsing xml received from a back end
    legacy system. The code is executed from a Session bean.
    Debugging learned me that the parse() method on the parser hangs the
    container without any error or exception trace. The code works fine outside
    a container.
    All help will be highly appreciated.
    Kurt

    I found out that the InputStream implementation used parsing source inside
    the container is different
    then from the one outside (other type of VM of course!). The Weblogic
    implementation blocks at the end of
    the stream, while the normal SUN JDK 1.3 returns. This is not a bug, the bug
    I found is in my proxy that allows
    the connection to the backend. This proxy allows HTTP connections, and I
    parse the XML received over HTTP.
    Regards,
    Kurt
    "Todd Karakashian" <[email protected]> wrote in message
    news:[email protected]..
    That's seems odd. Perhaps there is something going on in your document
    handler code that triggers a hang in the environment of the server.
    When you see the hang, instruct the VM to give you a thread dump (type
    control-<break> on Windows, <control>-\ (backslash) on UNIX in the
    window in which the server is running; the results are dumped to
    stderr). That will show what every thread in the server is doing. If you
    email or post the thread dump, I will take a look at it and see if I can
    see what is going on. Also, let us know which platform, VM, parser, and
    WebLogic version you are using.
    Regards,
    -Todd
    Kurt Quirijnen wrote:
    Hi,
    I am trying to use a Sax parser for parsing xml received from a back end
    legacy system. The code is executed from a Session bean.
    Debugging learned me that the parse() method on the parser hangs the
    container without any error or exception trace. The code works fine
    outside
    a container.
    All help will be highly appreciated.
    Kurt--
    Todd Karakashian
    BEA Systems, Inc.
    [email protected]

  • Help in Xml to abap

    hi aLL ,
    I have this code Xml code and i want to do parsing To internal table in abap ,
    how can i do that, inew to taht?
    please don't send link .
    Regards
    Nina
    this is the code that i write but i don't know what to do in :TRANSFORMATION simple_xml (Strans)
    How to write the code there that fits the XML value
    CALL TRANSFORMATION simple_xml
    SOURCE XML xml_field
    RESULT (gt_result_xml).
    <decisions><decision altkey = "0021" altvalue = "App"/><decision altkey = "0003" altvalue = "Reject"/></decisions>'

    Hi Nina,
    Following is the solution to parse xml "similar" to yours. I have replaced = with tags.
    XML:
    <decisions><decision><altkey>0021</altkey><altval>App</altval></decision><decision><altkey>0003</altkey><altval>Reject</altval></decision></decisions>
    ABAP Code
    REPORT  zakvtest_029.
    DATA xml_string TYPE string.
    DATA: BEGIN OF wa,
             akey TYPE string,
             aval TYPE string,
           END OF wa.
    DATA it_data LIKE TABLE OF wa.
    START-OF-SELECTION.
      xml_string =   `<decisions>`
                   &   `<decision>`
                   &     `<altkey>0021</altkey>`
                   &     `<altval>App</altval>`
                   &   `</decision>`
                   &   `<decision>`
                   &     `<altkey>0003</altkey>`
                   &     `<altval>Reject</altval>`
                   &   `</decision>`
                   & `</decisions>`.
      CALL TRANSFORMATION ztest_xml_002
           SOURCE  XML xml_string
           RESULT  itab = it_data.
    *break avishnoi.
      LOOP AT it_data INTO wa.
        WRITE:/ wa-akey,
                wa-aval.
      ENDLOOP.
    The transforamation is: (I have used Simple Transformation)
    <?sap.transform simple?>
    <tt:transform xmlns:tt="http://www.sap.com/transformation-templates">
      <tt:root name="ITAB"/>
      <tt:template>
        <decisions>
          <tt:loop name="a" ref=".ITAB">
            <decision>
              <altkey>
                <tt:value ref="$a.akey"/>
              </altkey>
              <altval>
                <tt:value ref="$a.aval"/>
              </altval>
            </decision>
          </tt:loop>
        </decisions>
      </tt:template>
    </tt:transform>
    Output
    0021 App
    0003 Reject
    Hope it helps a bit, you will need to work your way out for = "0021". Just play around and you will be there.
    Please post the final solution with code and transformation. Thank you,
    Regards,
    Aabhas
    Edited by: Aabhas K Vishnoi on Jul 27, 2009 10:16 AM

Maybe you are looking for

  • Labels in Pages?

    I still have the old Appleworks but cannot decipher instructions for making file folder labels. So I went to Pages '09 (4.0.3) & it appears that there is no way to make labels in Pages. Is this true? Given that it's true, is there a way to make file

  • How do I delete a search that is in the goole window they just stay there

    I use firefox for my main page it has a search window there when I type anything like ebay in it the next time when I go to it with another search ebay is still there and I cannot detete it without

  • Service Tax & VAT

    Hi, We are in Construction.The Job Contain Material as well as Service. Like Making of Drainage for that The Company Send the Po Which Contain Like Labour ,Cement every thing.As the Comapny DOn't do the Gr so they maintain it as Services .The Po Cona

  • Service Item and Delivered Item created by a kit (Lumf)

    Is there a way to get a Delivered item - TAN and a Service Item TAD on one Order by entering a Kit Item LUMF It creates the parent item as a TAP and both components as TAN.  I have the second component flagged as N non-stock in the BOM. Thanks Mark

  • Set up photo album in iPhone

    Hi, Could you please show me how to set up separate photo album in iphone? thanks!!