Using DOM

Hi everyone,
I was wondering if someone could give me a hand with the following.
I am planning to create a simple search engine to search for products for a computer parts retailer. The list of products is stored in an XML repository , and all queries to this repository are sent as XML documents.
The search engine web page will display a single text input field, into which a user can enter a keyword to search for
I am using DOM to convert the Html search query to an XML document.
Here is my DOM code so far.
<%@page import="java.io.*"%>
<%@page import="javax.xml.parsers.*"%>
<%@page import="org.w3c.dom.*"%>
<%@page import="org.apache.xml.serialize.*"%>
<%!
String 
search,textfield;
%>
<%
// Retrieve the Search query
search = request.getParameter("search");
textfield = request.getParameter("textField");
// Create a new DOM factory, and from that a new DOM builder object
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();// Note that we are creating a new (empty) document
Document document = builder.newDocument();
// The root element of our document wil be <query>
// It gets stored as the child node of the whole document (it is the root)
rootElement = document.createElement("query");
document.appendChild(rootElement);
// Create an <searchterm> element , place underneath <query>
Element searchtermElement = document.createElement("searchterm");
searchtermElement.appendChild(document.createTextNode(searchterm));
rootElement.appendChild(searchtermElem
I am just wondering if my DOM code looks correct so far?

A further cast didn't help either. For a change I have abandonded the JAXP approach and instead have built an example found at
http://otn.oracle.com/pub/listings/vohra_xmlschema_l4.html
that shows how to validate against a schema.
I have changed the method to return the validated document and have then tried to apply some of the D0M validation methods supposed to return a NameList but I still always get null.
I have posted the example Java program at
http://home.arcor.de/martin.honnen/java/xml/Test20040308.java.txt
and run it against the example schema and XML files at http://home.arcor.de/martin.honnen/java/xml/test20040307Xsd.xml http://home.arcor.de/martin.honnen/java/xml/test20040307.xml
While the parsing works and the XML is judged valid according to the schema attempts to use the DOM validation methods to return a NameList fail to return one.
Does anyone have an example using any DOM Level 3 validation interfaces/methods successfully?

Similar Messages

  • Problem in parsing XML using DOM Parser.

    Hi,
    I am parsing an XML using DOM Parser.
    When i try to get attributes of a node, i dont get in the order it is written. For Eg. This the node:
    <Level0 label="News" link="/website/ing_news.nsf/ViewNewsForm?OpenForm&All" level="202" uid="COGN-4MNMT3" parentid="aaaa">
    When i try to print the attribute values i should get in the order:
    News, /website/ing_news.nsf/ViewNewsForm?OpenForm&All, 202, COGN-4MNMT3, aaaa
    BUT I AM GETTING IN THE ORDER:
    News, 202, /website/ing_news.nsf/ViewNewsForm?OpenForm&All, aaaa, COGN-4MNMT3
    Is there any way to sort this problem out?
    Thanks and Regards,
    Ashok

    Hi Guys,
    Thanks a lot for your replies.
    But i want to keep all the values as attributes only.
    the XML file is as shown below:
    <Menu>
    <Level0 label="News" link="/website/ing_news.nsf/ViewNewsForm?OpenForm&All" level="202" uid="COGN-4MNMT3" parentid="aaaa" children="3">
         <Level1 label="ING News" link="" level="1" uid="COGN-4MNN89" parentid="COGN-4MNMT3" children="3" >
              <Level2 label="All ING News" link="/website/ing_news.nsf/ViewNewsForm?OpenForm&All" level="2" uid="INGD-4MVTK2" parentid="COGN-4MNN89" children="0">
              </Level2>
    </Level1>
    </Level0>
    The code i was using to get attributes is:
    String strElementName = new String(node.getNodeName());
         // System.out.println("strElementName:"+node.getNodeName());
    NamedNodeMap attrs = node.getAttributes();
    if (attrs != null) {
    int iLength = attrs.getLength();
    for (int i = 0; i < iLength; i++) {
    String strAttributes = (String) attrs.item(i).getNodeName();
    String strValues = (String) attrs.item(i).getNodeValue();
    Also is it not possible to Enforce the order using some Schema/DTD in this case?
    TIA
    Ashok

  • Problem in parsing JMS TextMessages using DOM

    Hi
    I want to parse JMS TextMessages by using DOM parser.DomBuilder's parse method supports only Strings,input stream in its constructor.
    Is there anyway we can parse JMS TextMessages by using DOM.Your help would be appreciated.
    Thanks
    Kanth

    kanth218 wrote:
    Hi
    DomBuilder's parse method supports only Strings,input stream in its constructor.This is not true. Have another look at the documentation.
    Is there anyway we can parse JMS TextMessages by using DOM.Your help would be appreciated.
    parse(new InputSource(new StringReader(someString)))

  • Parsing an XML using DOM parser in Java in Recursive fashion

    I need to parse an XML using DOM parser in Java. New tags can be added to the XML in future. Code should be written in such a way that even with new tags added there should not be any code change. I felt that parsing the XML recursively can solve this problem. Can any one please share sample Java code that parses XML recursively. Thanks in Advance.

    Actually, if you are planning to use DOM then you will be doing that task after you parse the data. But anyway, have you read any tutorials or books about how to process XML in Java? If not, my suggestion would be to start by doing that. You cannot learn that by fishing on forums. Try this one for example:
    http://www.cafeconleche.org/books/xmljava/chapters/index.html

  • Parsing xml using DOM parser in java

    hi there!!!
    i don have much idea about parsing xml.. i have an xml file which consists of details regarding indentation and spacing standards of C lang.. i need to read the file using DOM parser in java n store each of the attributes n elements in some data structure in java..
    need help as soon as possible!!!

    DOM is the easiest way to parse XML document, google for JDOM example it is very easy to implement.
    you need to know what is attribute, what is text content and what is Value in XML then easily you can parse your document with dom (watch for space[text#] in your XML document when you parse it).
    you get root node then nodelist of childs for root then go further inside, it is easy believe me.

  • Delete elements from XML file using DOM and java

    Hi
    I want now is to remove element from my XML file
    for example
    i have following xml
    <?xml version="1.0" encoding="UTF-8"?>
    <printing>
    <firstLineTexts>
              <firstLineText />
              <firstLineText>|line11</firstLineText>
              <firstLineText>|line12</firstLineText>
    </firstLineTexts>
    </printing>how do i remove all elements fireLineText
    my final output should be
    <?xml version="1.0" encoding="UTF-8"?>
    <printing>
    <firstLineTexts>
    </firstLineTexts>
    </printing>How do i do it using DOM,
    I can create instance of DOM and write it using TransformerFactory
    Ashish

    Hi
    I am trying the following code,
    but it is not working
                    NodeList nScene = doc.getElementsByTagName("firstLineTexts");
              NodeList nScene1 = nScene.item(0).getChildNodes();
              for (int i = 0; i < nScene1.getLength(); i++)
                   Node n = nScene1.item(i);
                        nScene.item(0).removeChild(n);
              }

  • Remove element from xml using dom.

    i want to remove an element from an xml file using dom.
    i remove the element but the whole content of the file is also deleted.
    how can i rewrite the file.

    vij_ay wrote:
    subject :Remove element from xml,but if empty element in input file then output should be <tag></tag>, not like <tag.xml/>I assume you mean <tag/> but why do you want this? Any application that will not accept this valid XML construct is flawed and a bug report should be raised against it.

  • How to remove element namespaces in XML file using DOM or SAX?

    Hi Guys,
    I developed a JAVA mapping in XI to add name spaces for XML file, after mapping,name spaces xmlns="http://www.mro.com/mx/integration" and xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" were added correctly, but for some nodes, such as <Header> and <Content>, a name space xmlns="" was added automatically.Please check below files to compare.
    It looks like be added automatically by XI. I didn't process anything for these nodes in JAVA program.
    Now the issue is, how can I remove these redundant namespaces? Such as xmlns="".
    Can I remove them using DOM or SAX in JAVA Mapping?
    Thanks in advance.
    ====>Original XML file
    <?xml version="1.0" encoding="UTF-8"?>
    <LLYLPPInterface language="EN">
       <Header>
          <SenderID>GBIP</SenderID>
          <CreationDateTime>2008-02-13T22:49:34-05:00</CreationDateTime>
          <RecipientID/>
          <MessageID/>
       </Header>
       <Content>
          <LLY-LPP>
             <INVOICE>
                <INVOICELINE>
                   <PONUM>4780000008</PONUM>
                   <POLINENUM>1</POLINENUM>
                   <INVOICEQTY>1</INVOICEQTY>
                   <LOADEDCOST>68</LOADEDCOST>
                </INVOICELINE>
             </INVOICE>
          </LLY-LPP>
       </Content>
    </LLYLPPInterface>
    ===>Target XML file after JAVA mapping
    <?xml version="1.0" encoding="utf-8"?>
    <LLYLPPInterface language="EN" xmlns="http://www.mro.com/mx/integration" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
         <Header xmlns="">
              <SenderID>GBIP</SenderID>
              <CreationDateTime>2008-02-13T23:11:55-05:00</CreationDateTime>
              <RecipientID/>
              <MessageID/>
         </Header>
         <Content xmlns="">
              <LLY-LPP>
                   <INVOICE>
                        <INVOICELINE>
                             <PONUM>4780000008</PONUM>
                             <POLINENUM>0</POLINENUM>
                             <INVOICEQTY>1</INVOICEQTY>
                             <LOADEDCOST>68</LOADEDCOST>
                        </INVOICELINE>
                   </INVOICE>
              </LLY-LPP>
         </Content>
    </LLYLPPInterface>
    Edited by: Eddie Zhang on Feb 14, 2008 9:22 AM
    Edited by: Eddie Zhang on Feb 14, 2008 9:24 AM

    Hi Milan,
    Thanks for your replay.
    Actually when I used module XMLAnonymizerBean to convert namespaces, the header of XML, such as <?xml version="1.0" encoding="UTF-8"?> was converted to format <?xml version='1.0' encoding='UTF-8'?>, quote was converted to single quote. Although I set parameter anonymizer.quote = ", it still didn't work, single quote appeared instead of quote.
    I'm not sure why this happened. Can anyone help to clarify this?
    Thanks
    Edited by: Eddie Zhang on Feb 15, 2008 2:11 AM

  • Convertion of flat file to XML using DOM

    Hi!
    I need help for convert a flat file to XML using DOM and by taking the validation of a specified DTD. Can any body help me in this regard.
    Bye,
    lat

    first you have to decide how the flat file will map to xml. Will you use attributes or pcdata for your fields, or both? Will there be a hierarchy, or will it be mostly flat?
    Once decided, you'd probably just use a BufferedReader to read the lines one at a time, and generate Dom nodes as appropriate, and stick them in the tree.

  • Need to retrieve all the node values of xml using DOM parser..pls help

    I want to fetch each node value in this xml file:
    <?xml version="1.0" encoding="UTF-8"?>
    <Main>
    <AAAAA>
    <ES>ESValue</ES>
    <EI>EIValue</EI>
    </AAAAA>
    <BBBBB>
    <SIP>
    <ST>STValue</ST>
    <TB>TBValue</TB>
    <PM>PMValue</PM>
    <VIP>
    <CARP>
    <AN1>AN1Value</AN1>
    <BN>BNValue</BN>
    </CARP>
    <DARP>
    <SA>
    <AN2>AN2Value</AN2>
    <CN>CNValue</CN>
    </SA>
    </DARP>
    </VIP>
    </SIP>
    </BBBBB>
    </Main>
    output should be the inner text values of diffrent nodes that contain some values..
    i.e
    output:
    ESValue
    EIValue
    STValue
    TBValue
    PMValue
    AN1Value
    BNValue
    AN2Value
    CNValue
    so that i can use thses node values and put it them in database...

    pls check the above xml file in proper redable order...I need to parse using DOM and fetch node values that are present...
    <?xml version="1.0" encoding="UTF-8"?>
    <Main>
        <AAAAA>
            <ES>ESValue</ES>
            <EI>EIValue</EI>
        </AAAAA>
        <BBBBB>
            <SIP>
                <ST>STValue</ST>
                <TB>TBValue</TB>
                <PM>PMValue</PM>
                <VIP>
                    <CARP>
                        <AN1>AN1Value</AN1>
                        <BN>BNValue</BN>
                    </CARP>
                    <DARP>
                        <SA>
                            <AN2>AN2Value</AN2>
                            <CN>CNValue</CN>
                        </SA>
                    </DARP>
                </VIP>
            </SIP>
        </BBBBB>
    </Main>

  • How to ignore empty text element while using DOM to parse xml??

    hi everyone,
    i am using DOM to parse an xml file. But i dont know how to cinfig the DocumentBuilderFactory to ignore empty text elements.
    For example, i have an xml file like this:
    <?xml version="1.0" encoding="UTF-8" ?>
    <root>
        <child>Tom</child>
        <child>Jerry</child>
    </root>I used the following codes to parse:
    String fname = "Tom-and-Jerry.xml";
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setIgnoringElementContentWhitespace(true);
    factory.setIgnoringComments(true);
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    // Generate a DOM tree from the DOM builder.
    org.w3c.dom.Document dom = builder.parse(new File(fname));
    org.w3c.dom.NodeList list = dom.getChildNodes();
    for (int i=0; i<list.getLength(); i++) {
        System.out.println("Child No."+i);
        System.out.println("NodeName="+list.item(i).getNodeName());
        System.out.println("NodeType="+getType(list.item(i).getNodeType()));
        System.out.println("NodeValue="+list.item(i).getNodeValue());
        System.out.println();
    }The result is not exactly what i want ---- there are 5 children in list!! The 1st, 3rd and 5th are #text and their values are all empty. Only the 2nd and the 4th are the child that i expect.
    It is really troublesome to get all these silly empty texts as sub elements. I tried to get rid of them, but i failed. I just dont understand why factory.setIgnoringElementContentWhitespace(true) did not work.
    Anyone can help me? thanks.
    Heavy ZHENG

    I just dont understand why factory.setIgnoringElementContentWhitespace(true) did not work.That only does something if the XML has a DTD that enables it to know what whitespace can be ignored and what is significant. The API documentation for the method refers you to this document:
    http://www.w3.org/TR/REC-xml#sec-white-space

  • Update XML using DOM parser

    I am using Dom parser in java to parse xml.I am able to retrive data from xml.Can any one help me in updating an xml when data is modified in the user interface.I am created interface in html with three fields namely UserName , LastLogin, Modified fields.If Admin person wants to modify any of these three fields , those changes should reflect in xml also.
    Thanks
    divya

    Code snippet
    ===========
    OutputFormat outputFormat = new OutputFormat("XML","ISO-8859-1",true);
    outputFormat.setDoctype(null,"emp.dtd")
    It adds the DOCTYPE element but doesnt create the .DTD file.
    <!DOCTYPE ROOT_EL SYSTEM "emp.dtd">
    Any ideas?
    Rgds,
    Seetesh

  • Converting into XML without using DOM

    Hi there,
    I need to generate a XML file on the fly, given a HashMap. It will be used later to feed into XSLT parser.
    Instead of using DOM parser which is memory intensive, I am generating the XML by appending the necessary into a String. For eg:
    StringBuffer st = new StringBuffer();
    sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    sb.append( "\n" );
    sb.append("<"+ transaction.getCode() + ">");
    ...........................so on
    I tried to gain resources in the book, but every example will actually use DOM to build a XML file.
    I am just thinking what is the repercussion if i do not use DOM.
    Could anyone please advice.
    Thanks.

    None really, if you don't need to walk the tree and have random access. Some find it hard to read / maintain, but I don't mind it. If you are just outputting to XSLT, what you are doing will work fine.

  • Writing XML using DOM

    Hi All,
    I am trying to create a XML file using DOM. After creating , when I am trying to display using System.out.print , It prints [getPrice: null ]
    Here is the code.
    import org.w3c.dom.*;
    import org.apache.xerces.parsers.DOMParser;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import java.io.File;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    public class DomParseWrite
         static Document doc = null;
         static Document newdoc = null;
         public DomParseWrite( String uri )
              try
                   DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                   DocumentBuilder db = dbf.newDocumentBuilder();
                   doc = db.parse(new File( uri ) );
                   newdoc = db.newDocument();
                   createDocument();
              catch (Exception e)
                   e.printStackTrace(System.err);
         public void createDocument()
              Element newRoot = newdoc.createElement( "getPrice" );
              NodeList getPrice = doc.getElementsByTagName( "item" );
              int length = getPrice.getLength();
              for( int itemIndex = 0 ; itemIndex < length ; itemIndex++ )
                   Node first = getPrice.item( itemIndex ).getFirstChild();
                   Element item = newdoc.createElement( "item" );
                   String itemName = first.getNodeValue() ;
                   item.appendChild( newdoc.createTextNode( itemName ) );
                   newRoot.appendChild( item );
                   String priceValue = "" ;
                   if( itemName.equals( "apple" ) )
                        priceValue = "10" ;
                   if( itemName.equals( "orange" ) )
                        priceValue = "5" ;
                   Element price = newdoc.createElement( "price" );
                   Node priceVal = newdoc.createTextNode( priceValue );
                   price.appendChild( priceVal );
                   newRoot.appendChild( price );
              System.out.println( " NEw DOcument is" );
              newRoot.normalize();
              System.out.println( newRoot.toString() );
         public static void main( String args[] )
              DomParseWrite dom = new DomParseWrite( args[0] );
    Can any one tell me what is the problem.
    Regards
    Smitha

    Hi,
    I am able to compile and I cross checked if the Document is created by parsing through the nodes.
    It is creating the document properly. But problem in displaying.
    I tried with JDK1.2 and xerces on win2000. But same problem. While displaying
    System.out.println( newRoot.toString() ). it displays
    [getPrice:null].
    Regards
    Smitha

  • How to parse using DOM parser:

    <employee>
         <name>phaneendra</name>
         <age>21</age>
         <company>ABC</company>
         <Authorization>
              <ID>21<ID>
              <Role>Normal</Role>
         </Authorization>
    </employee>
    I am using DOM Parser.Using that parser how can i wil get the <Authorization> node value as
    <Authorization>
         <ID>21<ID>
         <Role>Normal</Role>
    </Authorization>
    thanks in advance

    Since you seem new to using DOM, I'll first give a word of advice.
    Get very familiar with the JavaDocs for things like Document, Element, Node and Attribute. There is much wisdom in those files, especially in the table near the top of the Node interface. Pay particular attention to the meaning of nodeValue for various types on content.
    Using DOM, you get a Document.
    From a Document, you can use the getDocumentElement to get the root element (in your case, the one with a name of "employee").
    From an Element, to get to a child Element with a specific name, use getElementsByTagName or getElementsByTagNameNS (if your elements are coded with NameSpaces).
    Then get the first entry in the resulting list and process it however you like.

Maybe you are looking for

  • XML, nodeType = 1 and therefore nodeValue = null

    hello; I have an external XML file; I have successfully parsed through it and extracted attributes, nodeNames, and child arrays; however I am unable to get the nodeValues, even though when I simply trace out the node I get: <a_node>it's value</a_node

  • Screen size on a flat screen when a MacBook's connected

    I connect my MacBook to my Samsung TV through a DVI-HDMI cable. It works great, but when I set it to mirror diplays, the screen doesn't quite fit on the TV, not allowing me to see the menubar at all or some of the dock. I heard of a program to fix th

  • How do I scan for a virus? Internet won't often connect to facebook, google, youtube and many other websites while others connect fine.

    Serveral times a week I won't be able to connect with facebook, google, youtube and yahoo. Usually it will say: "Invalid URL The requested URL "/", is invalid. Reference #9.64070f17.1344033131.59fe68f5" I'm not even using a "/" in the address bar. I'

  • Need help on a while loop

    Hi...I am somewhat new to Java and I am trying to do a nested while loop. Basically I have a result set from a query and I want to loop though that result set BUT I need a second loop to put together 150 of the results at a time and add them to a Geo

  • WSDL for PI 7.1 wsdl:service

    Hi ALL, i have a sender SOAP to receiver ABAP proxy scenario. i got the WSDl file from sender agreement menu Display WSDL option and gave the WSDL to the to the .Net team.. they are telling me the WSDL file has some <wsdl:service name="XI_c23f13a4efb