Simple XML DOM Example Needed.

I need a simple XML DOM Example that reads in the XML and makes objects out of the elements. The tutorial from sun is very sketchy and seems to good far too quickly.
Thanks,
Dave.

You can find some examples:
http://java.sun.com/xml/jaxp/dist/1.0.1/examples/#building
http://newinstance.com/writing/javaxml2/javaxml2_examples.html
http://www.docuverse.com/domsdk/index.html#tutorial
http://www.devx.com/sourcebank/search.asp

Similar Messages

  • Need help with XML DOM example

    Im going through the DOM tutorial portion on displaying a DOM with a JTree and have a few questions
    http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JAXPDOM4.html
    lets say i have the following simple XML :
    <?xml version="1.0"?>
    <circle>
      <radius>15</radius>
      <position>
        <x-coordinate>30</x-coordinate>
        <y-coordinate>50</y-coordinate>
      </position>
    </circle>why do i get a 3 text nodes in the resulting JTree, not counting the text that are children of <radius>, <x-coordinate> and <y-coordinate> elements ?

    Is this true ? How can i avoid displaying empty text nodes ?
    The empty text elements are included because by default, DocumentBuilder creates a DOM that includes all the lexical information necessary to reconstruct the original document, in it's original form. That includes comment nodes as well as text nodes. There is as yet no standard mechanism for eliminating such lexical information in the DOM so you are left with the logical structure.

  • XML Dom example

    I am trying to parse an XML file in Java. I use the same XML file and am able to parse it easily in C# (hehehe I love mentioning that here ;) & VB. However, I am unable to find a decent tutorial for parsing XML DOM on the Java website. The example I have ties it into a Swing app and makes it needlessly complicated. Is there another tutorial for XML DOM? Can someone post some source code illustrating DOM?
    Thanks!

    That's the horrible example that I was referring to. It takes the reading of an XML document, using DOM, and creates a GUI app from it, making the example needlessly complicated.
    However, through experimentation and the java docs for JDK 1.4 I have figured out how to do what I need.

  • Simple SOAP+WSDL example needed

    I'm pretty much confused about SOAP and WSDL and can't find a good and simple example. I use Sun One Studio. How do I run some web service example.

    You can find some examples:
    http://java.sun.com/xml/jaxp/dist/1.0.1/examples/#building
    http://newinstance.com/writing/javaxml2/javaxml2_examples.html
    http://www.docuverse.com/domsdk/index.html#tutorial
    http://www.devx.com/sourcebank/search.asp

  • How to query a simple XML - any example?

    Folks, I have a below XML stored within table, column type XMLTYPE.
    I would like to extract all data from it by using some simple query + later insert returned rows into some dummy table.
    This should be an easy task for somebody who is using XML on daily basis.
    <env:Envelope xmlns:env='http://schemas.xmlsoap.org/soap/envelope/'>
      <env:Header></env:Header>
      <env:Body>
        <ns1:getVehiclesResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns1="http://wirelesscar.com/dynafleet/api/types">
          <result>
            <vehicleInfos>
              <displayName>TRUCK 1</displayName>
              <vehicleId>
                <id>15631444</id>
              </vehicleId>
            </vehicleInfos>
            <vehicleInfos>
              <displayName>TRUCK 2</displayName>
              <vehicleId>
                <id>1564652</id>
              </vehicleId>
            </vehicleInfos>
            <vehicleInfos>
              <displayName>TRUCK 3</displayName>
              <vehicleId>
                <id>15634543</id>
              </vehicleId>
            </vehicleInfos>
          </result>
        </ns1:getVehiclesResponse>
      </env:Body>
    </env:Envelope>XML is stored in table TEST_XML column XML_DATA:
    select  ...
               extract(dr.response_env, '//result/vehicleInfos/displayName/text()').getStringVal()
       from TEST_XMLI would like to extract all nodes from <result> through some query.
    Kind regards,
    Tomas

    the "extract" function is deprecated from 11g. You'd be better using XMLTABLE...
    e.g.
    SQL> ed
    Wrote file afiedt.buf
      1  WITH t as (select XMLTYPE('
      2  <RECSET xmlns:aa="http://www.w3.org">
      3    <aa:REC>
      4      <aa:COUNTRY>1</aa:COUNTRY>
      5      <aa:POINT>1800</aa:POINT>
      6      <aa:USER_INFO>
      7        <aa:USER_ID>1</aa:USER_ID>
      8        <aa:TARGET>28</aa:TARGET>
      9        <aa:STATE>6</aa:STATE>
    10        <aa:TASK>12</aa:TASK>
    11      </aa:USER_INFO>
    12      <aa:USER_INFO>
    13        <aa:USER_ID>5</aa:USER_ID>
    14        <aa:TARGET>19</aa:TARGET>
    15        <aa:STATE>1</aa:STATE>
    16        <aa:TASK>90</aa:TASK>
    17      </aa:USER_INFO>
    18    </aa:REC>
    19    <aa:REC>
    20      <aa:COUNTRY>2</aa:COUNTRY>
    21      <aa:POINT>2400</aa:POINT>
    22      <aa:USER_INFO>
    23        <aa:USER_ID>3</aa:USER_ID>
    24        <aa:TARGET>14</aa:TARGET>
    25        <aa:STATE>7</aa:STATE>
    26        <aa:TASK>5</aa:TASK>
    27      </aa:USER_INFO>
    28    </aa:REC>
    29  </RECSET>') as xml from dual)
    30  -- END OF TEST DATA
    31  select x.country, x.point, y.user_id, y.target, y.state, y.task
    32  from t
    33      ,XMLTABLE(XMLNAMESPACES('http://www.w3.org' as "aa"),
    34                '/RECSET/aa:REC'
    35                PASSING t.xml
    36                COLUMNS country NUMBER PATH '/aa:REC/aa:COUNTRY'
    37                       ,point   NUMBER PATH '/aa:REC/aa:POINT'
    38                       ,user_info XMLTYPE PATH '/aa:REC/*'
    39               ) x
    40      ,XMLTABLE(XMLNAMESPACES('http://www.w3.org' as "aa"),
    41                '/aa:USER_INFO'
    42                PASSING x.user_info
    43                COLUMNS user_id NUMBER PATH '/aa:USER_INFO/aa:USER_ID'
    44                       ,target  NUMBER PATH '/aa:USER_INFO/aa:TARGET'
    45                       ,state   NUMBER PATH '/aa:USER_INFO/aa:STATE'
    46                       ,task    NUMBER PATH '/aa:USER_INFO/aa:TASK'
    47*              ) y
    SQL> /
       COUNTRY      POINT    USER_ID     TARGET      STATE       TASK
             1       1800          1         28          6         12
             1       1800          5         19          1         90
             2       2400          3         14          7          5
    SQL>Have a go at applying that to your own XML, passing your own XMLTYPE data into the XMLTABLE and specifying your own Xquery paths
    (I provided you with an example with namespaces in it as they can be tricky too)

  • Help with simple XML reading example using StAX

    Please, could somebody help me with this issue?
    Or, could somebody point me to a comprehensive StAX tutorial?
    thanks!
    I have prepared a simple sample that looks like 'homework', but this newbie task is getting me crazy...
    I just want to store in the object Shop[] shopsArray; the next XML file, using StAX:
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <shops>
        <shop>
             <name>Amazon</name>
            <code>AMZ</code>
            <url>www.amazon.com</url>
            <product>
                <book>
                    <name>Core JSF</name>
                    <code>cojsf</code>
                    <price>136</price>
                    <pages>333</pages>
                </book>
            </product>
            <product>
                <book>
                    <name>Java forr Dummies</name>
                    <code>jfd</code>
                    <price>68</price>
                    <pages>400</pages>
                </book>
            </product>
            <product>
                <video>
                    <name>Braveheart</name>
                    <code>brvh</code>
                    <price>15</price>
                    <duration>3h</duration>
                </video>
            </product>
        </shop>
         <!-- <shop>Other types of shops</shop> -->
    </shops>Having the related classes below:
    public class Shop {
         String name;
         String code;
         String url;
         Product[] productsArray;
    public class Product {
         String name;
         String code;
         String price;
    public class Book extends Product {
         String pages;
    public class Video extends Product {
         String duration;
    }

    [http://vtd-xml.sf.net|http://vtd-xml.sf.net] While I am not an expert on StAX, I think you may be interested in vtd-xml to simplify coding as it
    supports random access and XPath
    http://vtd-xml.sf.net

  • XML DOM. Need the command to convert to real values.

    Hi,
    This is a sniplet of my code.
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = factory.newDocumentBuilder();
    Document doc = db.parse(new FileInputStream(MyXMLFile));
    NodeList list = doc.getElementsByTagName("log");
    Node root = list.item(0);
    return doc.toString() + list.toString() + root.toString();
    This is what gets returned.
    [email protected][email protected]@3411a
    How do I get the real value of "log"?
    Thanks in advance

    I have tried this and still returns blank.
              DocumentBuilderFactory docFac1 = DocumentBuilderFactory.newInstance();          
    DocumentBuilder db1 = docFac1.newDocumentBuilder();          
    Document doc1 = db1.parse(new FileInputStream(XMLFILE));          
    TransformerFactory tfac1 = TransformerFactory.newInstance();          
    StringWriter strWtr1 = new StringWriter();          
    StreamResult strResult1 = new StreamResult(strWtr1);          
    Transformer trans1 = tfac1.newTransformer();          
    trans.transform(new DOMSource(doc.getDocumentElement()), strResult1);          
    System.out.println(strResult1.getWriter().toString());          
    DocumentBuilder parser;
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {
    parser = factory.newDocumentBuilder();
    Node myNode = doc1.getElementsByTagName("properties").item(0);
    if (myNode != null) {
    NodeList propChildren = myNode.getChildNodes();
    int n = propChildren.getLength();
    for (int i=0;i<n;++i) {
    Node node = propChildren.item(i);
    if (node.getNodeType() == Node.ELEMENT_NODE) {
    NodeList nodeChildren = node.getChildNodes();
    int m = nodeChildren.getLength();
    Message = Message + "<" + node.getNodeName() + ">";
    for (int j=0;j<m;++j)
    if (nodeChildren.item(j).getNodeType() == Node.ELEMENT_NODE) {
    Node thisnode = nodeChildren.item(j);
    Message = Message + "<" + thisnode.getNodeValue() + ">";
    else
    Message = Message + "element <properties> not found";
    } catch (Exception e) {
    Message = Message + "trace ";
    e.printStackTrace();
    }

  • Simple XML parsing with DOM

    I have a XML file i need to parse. Can please someone give me a hint how to do this(please include code). Please note that im a new in XML and my DOM structure knowledge in limited(im confused from all the tutorials).
    XML code:
    <Vitals>
    <Hostname>sometest</Hostname>
    <IPAddr>sometest</IPAddr>
    <Kernel>sometest</Kernel>
    <Uptime>sometest</Uptime>
    <Users>sometest</Users>
    <LoadAvg>sometest</LoadAvg>
    </Vitals>
    <Network>
    <NetDevice>
    <Name>lo</Name>
    <RxBytes>10425010</RxBytes>
    <TxBytes>10425010</TxBytes>
    <Errors>0</Errors>
    <Drops>0</Drops>
    </NetDevice>
    <NetDevice>
    <Name>eth0</Name>
    <RxBytes>627976843</RxBytes>
    <TxBytes>2394415516</TxBytes>
    <Errors>271</Errors>
    <Drops>0</Drops>
    </NetDevice>
    </Network>
    So far ima at this step:
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {
    DocumentBuilder builder = factory.newDocumentBuilder();
    document = builder.parse( new File("NewFile.xml") );

    Just as simple text in console.
    Please give me the code.
    Is there any diference in document (DOM) if you create it with DFD or w/h ?
    So far i have this code, but it dosnt work for me(i get nothing as output:
    document = builder.parse( new File("NewFIle.xml") );
    NodeList list = document.getElementsByTagName("coffee");
    // Loop through the list.
    for (int k=0; k < list.getLength(); k++) {
    Node thisCoffeeNode = list.item(k);
    Node thisNameNode = thisCoffeeNode.getFirstChild();
    if (thisNameNode == null) continue;
    if (thisNameNode.getFirstChild() == null) continue;
    if (! (thisNameNode.getFirstChild() instanceof org.w3c.dom.Text)) continue;
    String data = thisNameNode.getFirstChild().getNodeValue();
    System.out.println(data);
    }

  • Need Jsp file to parse xml dom file

    Hai SDN member,
    I am new to jsp. I am having one xml dom file with follwing content,
    My XMLDOM file
    <root>
    <dir>
    <dirname>Mydir1</dirname>
    <file>
    <filename>f1</filename>
    </file>
    <file>
    <filename>f2</filename>
    </file>
    <dir>
    <dirname>mydir2</dirname>
    <file>
    <filename>f1</filename>
    </file>
    </dir>
    </dir>
    </root>
    This is my XML dom file. I need a sample jsp file which shoule parse the above content.
    Pls help me

    JSTL has an <x:parse> element, doesn't it? At any rate "I need JSP code" sounds very much like a JSP question to me. There's a JSP forum.

  • Fail to load Simple XML

    Hi Guys,
    Can any one help me loading a simple XML file into a Select list on JSP page. I found many examples but unable to load it the way I wanted it. I have a XML file with contents as;
    <examples>
    <example name='abc'>value here can be complete new xml document as well as a simple text and I want both to be shown in select list as 'text'</example>
    <example name='def'>value here can be complete new xml document as well as a simple text and I want both to be shown in select list as 'text'</example>
    <example name='ghe'>value here can be complete new xml document as well as a simple text and I want both to be shown in select list as 'text'</example>
    </examples>
    Now I want to parse this xml in my 'Select' HTML component in a way that I want the value of the element *<example>* (which can be a simple string or complete new XML (but I do not want to parse that XML and put it in a Select option as it is) and attribute name in each element/node as 'title' of the option in Select box just to provide some more info to user.
    Let me know if you guys need more information on this.
    Thanks,
    SJunejo

    There are many frameworks (castor, xmlbeans, jaxb etc) that helps you convert an xml to an object with corresponding properties. If you then place such an object in the proper scope, you can use a jsp (and jstl) easily to build your select tag.
    Or you can do it all by yourself - use an api like dom and extract the data into String objects and build up your own data Container to hold multiple String text and once again use jsp/jstl to build your tag.
    cheers,
    ram.

  • C/C++ OCI XML support examples

    Hi all,
    I'm trying to find some simple C/C++ examples of accessing XMLType columns from OCI. I'm interested in examples that show the basics like querying an XMLType column and inserting values into an XMLType column. I'm mainly interested in examples that deal with the XMLType column when the data is stored in the database as a CLOB though I'm not sure if the client side really cares about that.
    My application is based on the 9i OCI client since we still need to support that so I think that some of the newer OCI XML calls will not be available. I'm already quite familiar with programming in OCI, and I'm in the process of adding support for XML to our applicaiton so I just need some sample code that shows the basics and then hopefully I can figure things out from there.
    Any help would be much appreciated.
    Thanks,
    Nick

    It's possible to get XMLTYPE column in OCI without converting them to string or clob. I was able to do it by taking just the XDK headers and using only those functions declared there which are exposed by oci.dll directly. Here's the comment from my code:
    <tt>
    // Only calls which are defined in xmlproc.h (in xdb/include) as
    // #define XmlXYZ which take an xctx as first param, and cast back
    // xctx into xmlctxhead, then access the struct of function pointers,
    // are accessible to a pure OCI / Instance Client app.
    </tt>
    Crystal clear, no? ;-)
    The code below could be compiled with Instant Client augmented with xdk/include/*.h. It depends on a few classes and methods not listed (it's part of a bigger file), but if you program with OCI you should be able to replace them with something that works. It's quite rough, my own experimentation, before moving on to wrap all this messy C-code into nicer looking C++, but it shows that it can be done. Notice you need to init on Object mode, and given that it uses undocumented functions for the parsing, probably not supported at all by Oracle.
    Anyways, I hope its useful to someone. --DD
    PS: Sorry, looks like the forum garbles the code a little in HTML. don't know how to fix that. Maybe look at the source for the HTML.
    <tt>
    #include <xmlotn.h>
    * \brief Replacement for official XmlSaveDom not accessible to Instant-Clients
    * This method wraps calls to the unofficial XmlSaveDomVA method exposed by
    * Oracle contexts, to work around the fact that XmlSaveDom is not accessible
    * to applications deployed against Oracle's Instant Client runtime.
    * The real XmlSaveDom may be taking advantage of more undocumented key/value
    * pairs supported by underlying XmlSaveDomVA methods, to do proper error
    * handling possibly, which may explain why XmlSaveDomVA does not return the
    * number of bytes written, as advertised by XmlSaveDom's documentation.
    static xmldocnode* myXmlLoadDom(xmlctx* xctx, xmlerr* err, ...) {
    va_list v;
    va_start(v, err);
    xmldocnode*const rc = XmlLoadDomVA(xctx, err, v);
    va_end(v);
    return rc;
    static xmldocnode* load_dom_from_string(
    xmlctx* xctx, const char* doc_string, ub4 string_len
    SystemTimer timer;
    xmlerr err = XMLERR_OK;
    xmldocnode*const doc = myXmlLoadDom(
    xctx, &err,
    "buffer", doc_string,
    "buffer_length", string_len,
    NULL // sentinel marking end of key/value pairs
    if (err != XMLERR_OK || doc == NULL) {
    cerr << "Error parsing XML string" << endl;
    // throw?
    cout << "loaded dom in " << timer << endl;
    return doc;
    static xmldocnode* load_dom_from_file(
    xmlctx* xctx, const char* filename
    SystemTimer timer;
    xmlerr err = XMLERR_OK;
    xmldocnode*const doc = myXmlLoadDom(
    xctx, &err,
    "file", filename,
    NULL // sentinel marking end of key/value pairs
    if (err != XMLERR_OK || doc == NULL) {
    cerr << "Error parsing XML file " << filename << endl;
    // throw?
    cout << "loaded dom in " << timer << endl;
    return doc;
    static ubig_ora myXmlSaveDom(xmlctx* xctx, xmlerr* err, xmlnode* root, ...) {
    SystemTimer timer;
    va_list v;
    va_start(v, root);
    const ubig_ora rc = XmlSaveDomVA(xctx, err, root, v);
    va_end(v);
    cout << "saved dom in " << timer << endl;
    return rc;
    // TODO: On truncation, retry with increasingly larger heap buffer
    // and re-attempt serialization.
    static std::string save_dom_to_string(
    xmlctx* xctx, xmlnode* root,
    bool add_xmldecl = true,
    ub4 indent_step = 2,
    ub4 indent_level = 0,
    bool prune_children = false,
    const char* eol = "\n"
    xmlerr err = XMLERR_OK;
    const ub4 max_len = 2048;
    oratext doc_string[max_len] = {0};
    boolean xmldecl = add_xmldecl? TRUE: FALSE;
    boolean prune = prune_children? TRUE: FALSE;
    const ubig_ora byte_count = myXmlSaveDom(
    xctx, &err, root,
    "buffer", doc_string,
    "buffer_length", max_len,
    "xmldecl", xmldecl, // ignored
    "prune", prune,
    // Using UTF-16 yields an empty string.
    // Using AL32UTF8 adds XML decl previously missing (with encoding="UTF-8")
    // despite requesting no xmldecl explicitly (was ignored anyway...), but
    // only if passing the doc node, not the root node.
    "output_encoding", "AL32UTF8",
    //"eol", eol, // LPX-00019: property "eol" unknown
    "indent_step", indent_step,
    "indent_level", indent_level, // ignored
    NULL // sentinel marking end of key/value pairs
    // Number of bytes written not returned, as advertised.
    // So deduce silent truncation from the end of the string
    // (nor is err set to XMLERR_SAVE_OVERFLOW...)
    const bool was_truncated = doc_string[max_len - 1] == '\0'
    && doc_string[max_len - 2] != '\0';
    const size_t actual_len = strlen((const char*)doc_string);
    cout << "byte_count return = " << byte_count
    << "; actual length = " << actual_len
    << "; truncated = " << (was_truncated? "true": "false")
    << endl;
    if (err == XMLERR_OK && actual_len > 0) {
    if (was_truncated) {
    cerr << "Truncation during XML serialization to a string" << endl;
    return std::string((const char*)doc_string, actual_len);
    return std::string();
    static void xml_dom_basics_main(int argc, const char* argv[]) {
    SystemTimer* disconnect_timer; // time "shutdown"
    Environment env(OCI_OBJECT);
    env.connect(zusername, zpassword, zdatabase);
    SystemTimer timer; // don't time connecting to DB
    OCIError*const errhp = env.errhp;
    xmlctx*const xctx = OCIXmlDbInitXmlCtx(
    env.envhp, env.svchp, errhp,
    (ocixmldbparam *)0, 0
    if (!xctx) {
    checkerr(OCI_ERROR, errhp);
    // TODO: Manipulate XML context???
    // FIXME: Instant Client SDK does not ship with xml.h...
    // Following call compiles (because include xmlotn.h) but doesn't link
    // with Instant Client SDK, because oci.dll doesn't export this symbol.
    //const boolean is_unicode = XmlIsUnicode(xctx);
    ** Same issue here, XmlLoadDom not available from oci.dll...
    // Parse "dummy" document
    xmlerr err = XMLERR_OK;
    oratext doc_string[] = "<dummy/>";
    xmldocnode* doc = XmlLoadDom(
    xctx, &err,
    "buffer", doc_string,
    "buffer_length", sizeof(doc_string)-1,
    "validate", TRUE,
    NULL // sentinel indicating last key/value pair
    if (!doc) {
    cerr << "XML parsing failed: rc = " << err << endl;
    // Only calls which are defined in xmlproc.h (in xdb/include) as
    // #define XmlXYZ which take an xctx as first param, and cast back
    // xctx into xmlctxhead, then access the struct of function pointers,
    // are accessible to a pure OCI / Instance Client app.
    oratext* dummy_root = 0;//[] = "dummy";
    oratext* dummy_uri = 0;
    xmldtdnode* dummy_dtd = 0;
    xmlerr err = XMLERR_OK;
    xmldocnode* doc = XmlCreateDocument(
    xctx, dummy_uri, dummy_root, dummy_dtd, &err
    if (!doc) {
    cerr << "XML parsing failed: rc = " << err << endl;
    } else {
    oratext root_tag[] = "root";
    xmlelemnode* root = XmlDomCreateElem(xctx, doc, root_tag);
    XmlDomAppendChild(xctx, doc, root);
    oratext child_tag[] = "child";
    xmlelemnode* child = XmlDomCreateElem(xctx, doc, child_tag);
    XmlDomAppendChild(xctx, root, child);
    xmltextnode* text = XmlDomCreateText(xctx, doc, (oratext*)"foo");
    XmlDomAppendChild(xctx, child, text);
    // Add a second child, but without text
    child = XmlDomCreateElem(xctx, doc, child_tag);
    XmlDomAppendChild(xctx, root, child);
    xmlelemnode* root2 = XmlDomGetDocElem(xctx, doc);
    assert(root == root2);
    xmlnodelist* children = XmlDomGetElemsByTag(
    xctx, root, (oratext*)"child"
    ub4 child_count = XmlDomGetNodeListLength(xctx, children);
    if (child_count > 0) {
    xmlnode* child0 = XmlDomGetNodeListItem(xctx, children, 0);
    if (XmlDomHasChildNodes(xctx, child0)) {
    // I assume it's text
    xmlnode* text0 = XmlDomGetFirstChild(xctx, child0);
    const oratext* value = XmlDomGetNodeValue(xctx, text0);
    ub4 value2_length = 0;
    const oratext* value2 = XmlDomGetNodeValueLen(xctx, text0, 0, 0, &value2_length);
    cout << "value = " << value << "; #value2 = " << value2_length << endl;
    XmlDomFreeNodeList(xctx, children);
    oratext doc_string[2048];
    const ubig_ora byte_count =
    (*XML_CB(xctx)->XML_SAVE_DOM_VA_CB)(
    //XmlSaveDomVA(
    xctx, &err, root,
    "buffer", doc_string,
    "buffer_length", 2048,//sizeof(doc_string) - 1,
    NULL
    cout << "byte_count = " << byte_count << endl;
    if (err == XMLERR_OK && byte_count > 0) {
    doc_string[sizeof(doc_string) - 1] = '\0'; // just in case
    cout << "doc = \n" << doc_string << endl;
    const std::string root_string = save_dom_to_string(xctx, root);
    cout << "root = \n" << root_string << endl;
    const std::string doc_string = save_dom_to_string(xctx, doc, false, 2, 2, false, "\r\n");
    cout << "doc = \n" << doc_string << endl;
    xmldocnode* doc2 = load_dom_from_string(
    xctx, doc_string.c_str(), (ub4)doc_string.size()
    const std::string doc_string2 = save_dom_to_string(xctx, doc2);
    cout << "doc2 = \n" << doc_string2 << endl;
    XmlFreeDocument(xctx, doc);
    XmlFreeDocument(xctx, doc2);
    // Try accessing freed doc on purpose (Hmmm, works...)
    //const std::string doc_string3 = save_dom_to_string(xctx, doc2);
    //cout << "doc3 = \n" << doc_string3 << endl;
    // 28 KB file. If file doesn't exist, simply prints out an error
    cout << "\n\n===== Loading / parsing 28 KB XML file =====" << endl;
    xmldocnode* xsd = load_dom_from_file(xctx, "georaster.xsd");
    cout << "XSD = \n" << save_dom_to_string(xctx, xsd, false, 2, 2, true, "\r\n");
    XmlFreeDocument(xctx, xsd);
    // 1,870 KB
    cout << "\n\n===== Loading / parsing 1,870 KB XML file =====" << endl;
    xmldocnode* witsml1 = load_dom_from_file(
    xctx, "medium.xml"
    cout << "WITSML1 = \n" << save_dom_to_string(xctx, witsml1, false, 2, 2, true);
    XmlFreeDocument(xctx, witsml1);
    // 68,911 KB
    cout << "\n\n===== Loading / parsing 68,911 KB XML file =====" << endl;
    xmldocnode* witsml2 = load_dom_from_file(
    xctx, "big.xml"
    cout << "WITSML2 = \n" << save_dom_to_string(xctx, witsml2, false, 2, 2, true);
    XmlFreeDocument(xctx, witsml2);
    OCIXmlDbFreeXmlCtx(xctx);
    cout << "xml_dom_basics_main: " << timer << endl;
    // For some reason, disconnecting after reading a large XML file
    // is very slow... Loading the 68 MB file above, in about 8 seconds,
    // results in the shutdown to take around 28 seconds!!!
    disconnect_timer = new SystemTimer; // time "shutdown"
    cout << "\n\nDisconnecting from DB, terminating OCI environment... " << endl;
    cout << "'shutdown' time: " << *disconnect_timer << endl;
    delete disconnect_timer;
    template <class T> T* checkxml(T* node, xmlerr err) {
    xmlnode* xml_node = node;
    if (!xml_node) {
    throw std::runtime_error("null node");
    if (err != XMLERR_OK) {
    throw std::runtime_error("XML error code returned");
    return node;
    static void xml_dom_select_main(int argc, const char* argv[]) {
    const oratext charset[] = "AL32UTF8";
    Environment env(OCI_OBJECT, charset, charset);
    env.connect(zusername, zpassword, zdatabase);
    SystemTimer timer; // don't time connecting to DB
    OCIError*const errhp = env.errhp;
    xmlctx*const xctx = OCIXmlDbInitXmlCtx(
    env.envhp, env.svchp, errhp,
    (ocixmldbparam *)0, 0
    if (!xctx) {
    checkerr(OCI_ERROR, errhp);
    throw std::runtime_error("Cannot initialize XML context");
    // Allocate Statement Handle
    OCIStmt* selecthp = 0;
    checkerr(
    OCIHandleAlloc(
    (dvoid *) env.envhp, (dvoid **) &selecthp,
    OCI_HTYPE_STMT, 0, 0
    env.errhp
    // Prepare Statement
    const char *const sql = "SELECT id, doc FROM xml_tab";
    checkerr(
    OCIStmtPrepare(
    selecthp, env.errhp,
    (const OraText*)sql, (ub4) strlen(sql),
    (ub4) OCI_NTV_SYNTAX, (ub4) OCI_DEFAULT
    env.errhp
    // Defines
    ub4 id = 0;
    OCIDefine* define_id = 0;
    checkerr(
    OCIDefineByPos(
    selecthp, &define_id, env.errhp, 1, &id, sizeof(id), SQLT_UIN,
    (dvoid *) 0, (ub2 *) 0, (ub2 *) 0, OCI_DEFAULT
    env.errhp
    OCIDefine* define_doc = 0;
    checkerr(
    OCIDefineByPos(
    selecthp, &define_doc, env.errhp, 2, 0, sizeof(point_typ), SQLT_NTY,
    (dvoid *) 0, (ub2 *) 0, (ub2 *) 0, OCI_DEFAULT
    env.errhp
    OCIType* xmltype_tdo = 0;
    const oratext xmltype_name[] = "XMLTYPE";
    checkerr(
    OCITypeByName(
    env.envhp, env.errhp, env.svchp,
    0, 0, // schema name (default schema when 0)
    xmltype_name, (ub4)strlen((const char*)xmltype_name),
    0, 0, // version name (ignored)
    OCI_DURATION_SESSION,
    OCI_TYPEGET_ALL,
    &xmltype_tdo // connection (service specific)
    env.errhp
    xmldocnode* doc = 0;
    ub4 doc_size = 0;
    OCIInd* p_doc_ind = 0;
    ub4 doc_ind_size = 0;//(ub4)sizeof(point_ind);
    checkerr(
    OCIDefineObject(
    define_doc, env.errhp, xmltype_tdo,
    //(void**)&p_pt, &pt_size, (void**)&p_pt_ind, &pt_ind_size
    (void**)&doc, 0, (void**)&p_doc_ind, 0
    env.errhp
    // Execute (scalar) Select Statement
    checkerr(
    OCIStmtExecute(
    env.svchp, selecthp, env.errhp, (ub4) 0 /* specific to select... */, (ub4) 0,
    (CONST OCISnapshot *) NULL, (OCISnapshot *) NULL,
    OCI_DEFAULT
    env.errhp,
    OCI_NO_DATA // TODO: Test with a select that returns no rows,
    // and specifying 0 iters, to see if it returns
    // OCI_SUCCESS, or OCI_NO_DATA
    // TODO: Describe the select-list.
    // TODO: Fix this screwed up logic!
    sword fetch_rc = OCI_NO_DATA;
    size_t row_count = 0;
    do {
    checkerr(
    fetch_rc = OCIStmtFetch2(
    selecthp, env.errhp, (ub4)1,
    (ub2)OCI_FETCH_NEXT, (sb4)0, (ub4)OCI_DEFAULT
    env.errhp, OCI_NO_DATA
    if (fetch_rc != OCI_NO_DATA) {
    ++row_count;
    if (p_doc_ind && *p_doc_ind == OCI_IND_NULL) {
    cerr << "\nXML doc#" << id << " is NULL" << endl;
    continue;
    cout << "\nXML doc#" << id << ":\n" << save_dom_to_string(xctx, doc) << endl;
    while (fetch_rc != OCI_NO_DATA);
    if (doc != NULL) {
    // When last row contained no document (NULL in XMLTYPE column),
    // the doc pointer is somehow reset to 0, and OCIObjectFree complains
    // about it: OCI-21560: argument 3 is null, invalid, or out of range
    checkerr(
    OCIObjectFree(env.envhp, env.errhp, doc, 0),
    env.errhp
    // Necessary to free documents when selecting XMLTYPE,
    // sinced used OCIObjectFree above?
    //XmlFreeDocument(xctx, doc);
    // Free Statement Handle
    checkerr(
    OCIHandleFree(selecthp, OCI_HTYPE_STMT),
    env.errhp
    OCIXmlDbFreeXmlCtx(xctx);
    cout << "xml_dom_select_main: " << timer << endl;
    static void xml_dom_insert_main(int argc, const char* argv[]) {
    Environment env(OCI_OBJECT);
    env.connect(zusername, zpassword, zdatabase);
    SystemTimer timer; // don't time connecting to DB
    OCIError*const errhp = env.errhp;
    xmlctx*const xctx = OCIXmlDbInitXmlCtx(
    env.envhp, env.svchp, errhp,
    (ocixmldbparam *)0, 0
    if (!xctx) {
    checkerr(OCI_ERROR, errhp);
    throw std::runtime_error("Cannot initialize XML context");
    xmlerr err = XMLERR_OK;
    xmldocnode* doc = checkxml(XmlCreateDocument(xctx, 0, 0, 0, &err), err);
    xmlelemnode* root = checkxml(XmlDomCreateElem(xctx, doc, (oratext*)"root"), err);
    XmlDomAppendChild(xctx, doc, root);
    xmlattrnode* version = checkxml(XmlDomCreateAttr(xctx, doc, (oratext*)"version", (oratext*)"0.1"), err);
    XmlDomAppendChild(xctx, root, version);
    xmlelemnode* child = checkxml(XmlDomCreateElem(xctx, doc, (oratext*)"child"), err);
    XmlDomAppendChild(xctx, root, child);
    xmltextnode* text = checkxml(XmlDomCreateText(xctx, doc, (oratext*)"baz"), err);
    XmlDomAppendChild(xctx, child, text);
    // Add a second child, but without text
    child = checkxml(XmlDomCreateElem(xctx, doc, (oratext*)"child"), err);
    XmlDomAppendChild(xctx, root, child);
    xmlattrnode* empty = checkxml(XmlDomCreateAttr(xctx, doc, (oratext*)"empty", (oratext*)"true"), err);
    XmlDomAppendChild(xctx, child, empty);
    const std::string doc_string = save_dom_to_string(xctx, doc);
    cout << "doc = \n" << doc_string << endl;
    // Insert this document into the DB
    // Allocate Statement Handle
    OCIStmt* selecthp = 0;
    checkerr(
    OCIHandleAlloc(
    (dvoid *) env.envhp, (dvoid **) &selecthp,
    OCI_HTYPE_STMT, 0, 0
    env.errhp
    // Prepare Statement
    const char *const sql = "INSERT INTO xml_tab (id, doc) VALUES (:1, :2)";
    checkerr(
    OCIStmtPrepare(
    selecthp, env.errhp,
    (const OraText*)sql, (ub4) strlen(sql),
    (ub4) OCI_NTV_SYNTAX, (ub4) OCI_DEFAULT
    env.errhp
    // Binds
    ub4 id = 101;
    OCIBind* bind_id = 0;
    checkerr(
    OCIBindByPos(
    selecthp, &bind_id, env.errhp, 1, &id, sizeof(id), SQLT_UIN,
    (dvoid *) 0, (ub2 *) 0, (ub2 *) 0, (ub4) 0, (ub4 *) 0, OCI_DEFAULT
    env.errhp
    OCIBind* bind_doc = 0;
    checkerr(
    OCIBindByPos(
    selecthp, &bind_doc, env.errhp, 2, 0, sizeof(point_typ), SQLT_NTY,
    (dvoid *) 0, (ub2 *) 0, (ub2 *) 0, (ub4) 0, (ub4 *) 0, OCI_DEFAULT
    env.errhp
    OCIType* xmltype_tdo = 0;
    const oratext xmltype_name[] = "XMLTYPE";
    checkerr(
    OCITypeByName(
    env.envhp, env.errhp, env.svchp,
    0, 0, // schema name (default schema when 0)
    xmltype_name, (ub4)strlen((const char*)xmltype_name),
    0, 0, // version name (ignored)
    OCI_DURATION_SESSION,
    OCI_TYPEGET_ALL,
    &xmltype_tdo // connection (service specific)
    env.errhp
    //xmldocnode* doc = 0;
    ub4 doc_size = 0;
    OCIInd doc_ind = OCI_IND_NOTNULL;
    OCIInd* p_doc_ind = &doc_ind;
    ub4 doc_ind_size = 0;//(ub4)sizeof(point_ind);
    checkerr(
    OCIBindObject(
    bind_doc, env.errhp, xmltype_tdo,
    //(void**)&p_pt, &pt_size, (void**)&p_pt_ind, &pt_ind_size
    (void**)&doc, 0, (void**)&p_doc_ind, 0
    env.errhp
    // Execute (scalar) Select Statement
    checkerr(
    OCIStmtExecute(
    env.svchp, selecthp, env.errhp, (ub4) 1, (ub4) 0,
    (CONST OCISnapshot *) NULL, (OCISnapshot *) NULL,
    OCI_DEFAULT
    env.errhp,
    OCI_NO_DATA // TODO: Test with a select that returns no rows,
    // and specifying 0 iters, to see if it returns
    // OCI_SUCCESS, or OCI_NO_DATA
    // Commit transaction
    checkerr(
    OCITransCommit(env.svchp, env.errhp, 0),
    env.errhp
    XmlFreeDocument(xctx, doc);
    OCIXmlDbFreeXmlCtx(xctx);
    cout << "xml_dom_insert_main: " << timer << endl;
    </tt>

  • Simple xml config file

    I have created a simple config file using something like:
          XMLEncoder e = new XMLEncoder(
                                      new BufferedOutputStream(
                                          new FileOutputStream("Config.xml")));
          e.writeObject(base.toString());
          e.writeObject(numberFrom);
          e.writeObject(numberTo);
          e.writeObject(numberPad);
          e.writeObject(maxTasks);
          e.writeObject(maxSubTasks);
          e.writeObject(textFrom);
          e.writeObject(textTo);
          e.close();which produces a file like:
    <?xml version="1.0" encoding="UTF-8"?>
    <java version="1.4.2_05" class="java.beans.XMLDecoder">
    <string>C:\</string>
    <int>1</int>
    <int>20</int>
    <int>2</int>
    <int>0</int>
    <int>1</int>
    <string>a</string>
    <string>z</string>
    </java> I want to make it a bit more version proof so need to get something more like:
    <?xml version="1.0" encoding="UTF-8"?>
    <program name=myprog>
    <dir>C:\</dir>
    <version>1</version>
    <myval1>20</myval1>
    <myval2>2</myval2>
    </program>There's probably loads of errors in that bit;) but you get the idea. I'm a bit new to xml programming.
    Can anyone give me any urls of help or examples that might do this?
    Thanks,
    David.

    You could use a binding api such as JAXB or xmlbeans. In essence these apis abstract the xml as pure java objects. Alternatively you could use an xml parser such as dom4j and build the XML 'by hand'. This class will create an example config file and write it to the file system
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import org.apache.xml.serialize.OutputFormat;
    import org.apache.xml.serialize.XMLSerializer;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Text;
    * Class to create a simple xml config file using W3C api
    * @author wollnyj
    public class CreateConfig {
         * create the config file
         *?xml version="1.0" encoding="UTF-8"?>
         *<program name=myprog>
         *    <dir>C:\</dir>
         *    <version>1</version>
         *    <myval1>20</myval1>
         *    <myval2>2</myval2>
         *</program>
         * @param configFile
         * @throws ParserConfigurationException
         * @throws IOException
        public CreateConfig(String configFile) throws ParserConfigurationException, IOException {
            //Document doc = parseXml(configFile);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            Document doc = factory.newDocumentBuilder().newDocument();
            Element program = doc.createElement("program");
            program.setAttribute("name","myprog");
            Element dir = createEle("dir","c:\\",doc);
            Element version = createEle("version","1",doc);
            Element val1 = createEle("myval1","20",doc);
            // etc...
            program.appendChild(dir);
            program.appendChild(version);
            program.appendChild(val1);
            doc.appendChild(program);
            write(doc,new File(configFile));
         * @param args
         * @throws Exception
        public static void main(String[]args) throws Exception {
            CreateConfig create = new CreateConfig("F:\\config.xml");
         * Write an xml document to the file system
         * @param document The document to be written
         * @param xmlFile The output file
         * @throws IOException The file does not exist or could not be created
        private void write(Document document, File xmlFile) throws IOException {
            OutputFormat format = new OutputFormat(document);
            format.setIndent(4);
            format.setLineSeparator(System.getProperty("line.separator"));
            format.setLineWidth(80);
            FileWriter writer = new FileWriter(xmlFile);
            XMLSerializer fileSerial = new XMLSerializer(new BufferedWriter(writer), format);
            fileSerial.asDOMSerializer();
            fileSerial.serialize(document);
        private Element createEle(String name, String value, Document doc) {
            Element ele = doc.createElement(name);
            Text textNode = doc.createTextNode(value);
            ele.appendChild(textNode);
            return ele;
    }

  • Change over from a simple Xml call to a rpc-Http call ....

    Hi there,
    I need to change over from a simple Xml call:
    <mx:XML id="urlsGeneral" source="http://www.mySite.com//.../AFS.xml"/>
    to a rpc-Http call which is updating the readout if Xml is changed at any time.
    I forgot to mention the most important item yet a very simple one: I need this only to be displayed in a title etc, and NOT a datagrid or else example below.
    title="{urlsGeneral.urlGeneral.(@name==0).age}
    I tried a lot today, but just can't get it right as the id="urlsGeneral" is always the problem.
    Any help would be appriciated !!! Thanks in advance. regards aktell2007
    <urlsGeneral>
    <urlGeneral>
    <name>Jim</name>
    <age>32</age>
    </urlGeneral>
    <urlGeneral>
    <name>Jim</name>
    <age>32</age>
    </urlGeneral>
    </urlsGeneral>
    Another call:
    <mx:Script>
    <![CDATA[
    import mx.collections.ArrayCollection;
    import mx.rpc.events.ResultEvent;
    public var myData:ArrayCollection;
    protected function myHttpService_resultHandler(event:ResultEvent):void {
    myData = event.result.urlsGeneral.urlGeneral;
    ]]>
    </mx:Script>
    <mx:HTTPService
    id="myHttpService"
    url="http://www.mySite.com//..../AFS.xml"
    result="myHttpService_resultHandler(event)"/>
    Preferable I wanted something like this to work:
    <mx:Script>
    <![CDATA[
    import mx.rpc.events.FaultEvent;
    import mx.managers.CursorManager;
    import mx.controls.Alert;
    import mx.rpc.events.ResultEvent;
    import mx.rpc.xml.SimpleXMLDecoder;
    // Don't use here as it is already used in .swc !
    /* import mx.rpc.http.HTTPService; */
    private var myHTTP:HTTPService;
    private function initConfigCall():void {
    myHTTP = new HTTPService();
    myHTTP.url = "com/assets/data/changesAppAIRPIOne001.xml";
    myHTTP.send();
    myHTTP.resultFormat = "xml";
    myHTTP.addEventListener(ResultEvent.RESULT, resultHandler);
    myHTTP.addEventListener(FaultEvent.FAULT, faultHandler);
    CursorManager.setBusyCursor();
    private function resultHandler(evt:ResultEvent):void {
    var xmlStr:String = evt.result.toString();
    var xmlDoc:XMLDocument = new XMLDocument(xmlStr);
    var decoder:SimpleXMLDecoder = new SimpleXMLDecoder(true);
    var resultObj:Object = decoder.decodeXML(xmlDoc);
    // Removed [0] on single node !
    appUpdateAvl.text = resultObj.application.configApp.appNewUpDate;
    appLastChanged.text = resultObj.application.configApp.appLastChanged;
    appChangedSections.text = resultObj.application.configApp.appChangedSections;
    CursorManager.removeBusyCursor();
    myHTTP.disconnect();
    private function faultHandler(event:mx.rpc.events.FaultEvent):void {
    var faultInfo:String="fault details: "+event.fault.faultDetail+"\n\n";
    faultInfo+="fault faultString: "+event.fault.faultString+"\n\n";
    mx.controls.Alert.show(faultInfo,"Fault Information");
    var eventInfo:String="event target: "+event.target+"\n\n";
    eventInfo+="event type: "+event.type+"\n\n";
    mx.controls.Alert.show(eventInfo,"Event Information");
    CursorManager.removeBusyCursor();
    myHTTP.disconnect();
    ]]>
    </mx:Script>

    Hi again,
    These days there are more quetions than answeres on any forum, and very seldom anybody shares the answer if they lucky enough to work it out so here is my answer for the above question
    Change over from a simple Xml call to a rpc-Http call ....
    I had it all along as a commend noted: // Removed [0] on single node !
    So instead of title="{urlsGeneral.urlGeneral.(@name==0).age} it would be now title="{resultObj.urlsGeneral.urlGeneral.[0].age} and now it works perfectly well. I hope that one or the other of you can use the answer and the code !!! regards aktell2007

  • Writing a simple XML editor

    I need to write a simple XML/SVG code editor for my application. I basically want to display the contents of an XML DOM so that if the user changes the text in the editor the DOM will be updated to reflect this.
    What would be the best way to do this?

    http://www.google.com/search?hl=en&lr=&ie=UTF-8&oe=UTF-8&q=XML+SVG+site%3Asourceforge.net

  • Simple XML Proof of Concept

    I like to do a simple proof of concept. As I am new to XML not sure if it can be done or not....Assumptions are that I am offline and what all I have is Browser in my laptop.
    1. I have a simple XML file that has data from Employee Table. I do also have a style sheet to display this data. SO I can use my browser to display this data.
    2. After displaying this data I like to add a new employee from the same broser. Once entered new emplyee I like to hit submit that should include this new employee into the orignal XML file or could create a new one.
    What are the best ways to approach this?? Again the assumptions are that what all I have is a browser that supports XML and Javascript.
    Thanks in advance...

    Thanks for your time Steve.
    There is not going to be any middle tier/OAS. As I explained I have
    1. XML Data File with Stylesheet in client.
    2. I have Browser that supports XML and JavaScript
    3. I need to display the data(For example Employee Data) from above file. Have the user change/include a DEPTNO for a specific employee, and then save the updated data to a new/existing XML file.
    Is this possible

Maybe you are looking for