Dom vs. document.getElementsByTagName

Okay, since you guys are so helpful and smart, here's another
one that's got me stumped. Why does dom.getElementsByTagName work
when assigned to a variable, but document.getElementsByTagName
doesn't? Example below.
function reportSkuCondMeta() {
// Read current document's SKU_Condition meta tag
var dom = dw.getDocumentDOM(); // get the dom of the current
document
var skuCondMeta = dom.getElementsByTagName("meta");
for ( counter = 0; counter < skuCondMeta.length;
counter++)
if (skuCondMeta[counter].name == "SKU_Condition") // now I
want the DOM of the extension form
// the following code returns error "displaySku has no
properties"
var displaySku = document.getElementsByTagName("input");
for ( iter = 0; iter < displaySku.length; iter++)
if (document.displaySku[iter].name == "sku_cond")
document.displaySku[iter].value =
skuCondMeta[counter].content;
// the following code runs just fine
/* for ( iter = 0; iter <
document.getElementsByTagName("input").length; iter++)
if (document.getElementsByTagName("input")[iter].name ==
"sku_cond")
document.getElementsByTagName("input")[iter].value =
skuCondMeta[counter].content;
Of course, for ease of formatting and elegance, I want to do
the first of the two uses of document.getElementsByTagName, but I
can't get it to work. Any ideas on this would be great.
Thanks!
-Scott

SAX is as usefull as DOM. i first started using DOM because of the nice object model. you just have one document object and can traverse the DOM tree, look for elements, change them, etc. the drawback: it's one single object that can get very big for big XML files.
this is where SAX comes in handy. e.g. you have a (not too small) xml file and want to process it (e.g. read all elements, process them sequentially or by record). the drawback: you have to implement a event listener class to catch the events for each sequential node.
conclusion:
* use DOM for
- small XMLs
- XMLs to change and write back to a file (or another stream)
* use SAX for
- larger XML
- XMLs you want to process sequentially
example: read XML content from a URL, convert the data to create SQL statements, insert the data. if you can't be sure that you always get only small results, i would prefer SAX as you need to read each node anyway and are independent of the XML length. (it's also a memory issue).

Similar Messages

  • Error: document.getElementsByTagName("head")[0] is undefined

    javascript crash
    Error: document.getElementsByTagName("head")[0] is undefined
    How can ı solve this problem

    Start Firefox in <u>[[Safe Mode]]</u> to check if one of the extensions is causing the problem (switch to the DEFAULT theme: Firefox (Tools) > Add-ons > Appearance/Themes).
    *Don't make any changes on the Safe mode start window.
    *https://support.mozilla.com/kb/Safe+Mode
    *https://support.mozilla.com/kb/Troubleshooting+extensions+and+themes
    If it does work in Safe-mode then disable all extensions and then try to find which is causing it by enabling one at a time until the problem reappears.
    *Use "Disable all add-ons" on the [[Safe mode]] start window to disable all extensions.
    * Close and restart Firefox after each change via "File > Exit" (Mac: "Firefox > Quit"; Linux: "File > Quit")

  • Adding attachments to xml dom generated documents

    Hello All,
    I am trying to add an attachment to a DOM generated XML document, does anyone have any idea as to how I amy be able to do this.

    Hi
    Happen to see your posting. Did you get any response for your question. I have a similar requirement. If you have any pointers, please let me know. Thanks for your help in advance.
    Regards
    Sri

  • Org.w3c.dom.Document.getElementById() not working for me

    I am having trouble using the .getelementById for the org.w3c.dom.Document class. I have devised a workaround, but was wondering what I have been doing wrong in the first place.
    My XML file contains, in part, a bunch of "sections" as outlined below:
    <section id="uniqueString">
       <icon ... />
       <window ... />
    </section>I want to get a "section" whose ID is String s . I tried using .getElementById()
    // document is of class org.w3c.dom.Document, and has parsed in an XML file
    // String s = "uniqueString"
    Element e = document.getElementById(s);However, e is null every time I run this. I have tried it with different Strings which look for other XML tags, but it always is null . I have devised a workaround:
    NodeList sections = document.getElementsByTagName("section");
    for (int i = 0; i < sections.getLength(); ++i) {
         if (((Element) sections.item(i)).getAttribute("id").equals(s)) {
              e = (Element) sections.item(i);
    // Do something with eSo the functionality I need is there; however, I was just wondering if anybody sees what I'm doing wrong in the attempt to use getElementById(). It's not essential that I find out, however it would improve my program's readability, probably improve the efficiency, and help me understand whatever concept I seem to be missing. I have been all through the javadoc online and I can't seem to figure out what's up with it.

    This is a user error. If it is any consolation, it is not uncommon.
    By "Id" this method looks for the attribute defined in the schema for this kind of XML file as an ID. It may or may not be "id".
    The JavaDoc for this method says:
    Attributes with the name "ID" or "id" are not of type ID unless so defined.
    So, you could have an attribute "programnum" defined as an ID in the schema, and find a value of that attribute with the getElementById() method.
    Dave Patterson

  • Use DOM as an argument of  XSLT document() function

    I have in memory several DOM documents. I have not stored in file system the XML files that are represented by these DOMs. I want to process with a stylesheet
    all of these DOMs (as DOMSource's) using document() function from the stylesheet. How can I refer to the secondary DOMs from document function if I haven't the files?
    F.e.
    <xsl:value-of select="document('file.xml')/.../..."/> file.xml only exists loaded in memory as DOM.
    Can anybody help me?? Thanks

    Thank you DrClap but I'm not sure about the use of URIResolver:
    if my xslt:
    <xsl:value-of select="document('file1.xml')\...\..."/>
    <xsl:value-of select="document('file2.xml')\...\..."/>
    I must define my own class that implements URIResolver and write my own resolve method, isn't it?
    class Resuelve implements URIResolver{
         private Document doc1;
         private Document doc2;
         public Resuelve(Document doc1, Document doc2){
              this.doc1 = doc1;
              this.doc2 = doc2;
         public Source resolve(String href, String base){
              if(base.equalsIgnoreCase("file1.xml")){
                   Source s1 = new DOMSource(doc1);
                   return s1;
              else if(base.equalsIgnoreCase("file2.xml")){
                   Source s2 = new DOMSource(doc2);
                   return s2;
              else{
                   return null;
    I suppose that XSLT processor use automatically resolve method. I don't understand the href parameter...
    Is this class correct? if not, can you show me an example please?
    Thank you very much

  • Document array has no properties

    Why doesn't DW8 like document arrays assigned to variables?
    Using the syntax,
    formInput = document.getElementsByTagName("input")
    Returns an error saying "formInput has no properties."
    Here's the full example:
    var dom = dw.getDocumentDOM();
    // get the current document's SKU_Condition meta tag
    var skuCondMeta = dom.getElementsByTagName("meta");
    for ( counter = 0; counter < skuCondMeta.length;
    counter++)
    if (skuCondMeta[counter].name == "SKU_Condition") // so far
    so good
    // get dom of the extension html form and assign the sku
    cond to the input field value
    /* why doesn't this code work?
    var formInput = document.getElementsByTagName("input");
    for ( iter = 0; iter < formInput.length; iter++)
    if (formInput[iter].name == "sku_cond")
    formInput[iter].value = skuCondMeta[counter].content;
    /* instead, I have to do this */
    for ( iter = 0; iter <
    document.getElementsByTagName("input").length; iter++)
    if (document.getElementsByTagName("input")[iter].name ==
    "sku_cond")
    document.getElementsByTagName("input")[iter].value =
    skuCondMeta[counter].content;
    Thanks for the help!
    -Scott

    I'm trying to use a calendar in my jsp pages. The code
    of that calendar is in a js file and is writen in
    JavaScript. I call the function from a html tag:
    <input type="text" name="date" id="date">
    Click
    here to enter a date
    In the js file there is a function
    show_calendar(textfieldname, dir)
    and lines
    var txtboxObj = textfieldname;
    and
    document.getElementById(txtboxObj).value =
    getdate(d,m,y);
    My problem now is that when I use Netscape 7.01 the
    calendar is not passing data to the input field in the
    parent window and I get the message:
    Error: document.getElementById(txtboxObj) has no
    properties
    In IE it is working with no problems.Obviously a JS problem. Go to a Javascript forum. You will be more likely to find people who know.

  • Using DOM to parse SOAP fault doesn't work properly

    why, when I run the following:
    import java.io.IOException;
    import org.xml.sax.SAXException;
    import org.xml.sax.helpers.DefaultHandler;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import org.w3c.dom.Document;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    public class ParseFaultDom {
    public void operation(String uri) {
    System.out.println("Parsing XML File: " + uri + "\n\n");
    String faultCode = "";
    String faultString = "";
    try {
    DocumentBuilderFactory factory =
    DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(uri);
    // should only be one apiece here
    NodeList faultCodes = document.getElementsByTagName("faultcode");
    NodeList faultStrings=document.getElementsByTagName("faultstring");
    Node codeNode = faultCodes.item(0);
    Node stringsNode = faultStrings.item(0);
    faultCode = codeNode.getNodeValue();
    faultString = stringsNode.getNodeValue();
    System.out.println("code: " + faultCode);
    System.out.println("string: " + faultString);
    } catch(ParserConfigurationException e) {
    System.out.println("Error creating parser: " + e.getMessage( ));
    } catch(IOException e) {
    System.out.println("Error reading URI: " + e.getMessage( ));
    } catch (SAXException e) {
    System.out.println("Error in parsing: " + e.getMessage( ));
    public static void main(String[] args) {
    if (args.length != 1) {
    System.out.println("Usage: java ParseFault [XML URI]");
    System.exit(0);
    String uri = args[0];
    ParseFaultDom pfd = new ParseFaultDom();
    pfd.operation(uri);
    giving it the following xml file as input:
    <?xml version='1.0' encoding='UTF-8'?>
    <s:Envelope xmlns:s="http://www.w3.org/2001/06/soap-envelope/"
    xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/1999/XMLSchema">
    <s:Body>
    <s:Fault>
    <faultcode xsi:type="xsd:string">Client</faultcode>
    <faultstring xsi:type="xsd:string">
    Invalid value given for identifier field: "-1".
    </faultstring>
    <details>
    <a>a</a>
    <b>b</b>
    <c>c</c>
    </details>
    </s:Fault>
    </s:Body>
    </s:Envelope>
    do I get the following output:
    Parsing XML File: fault.xml
    code: null
    string: null
    In other words, it finds the tags I'm looking for, but it isn't getting the tag value, apparently.... I can add more instances of each tag, or delete them altogether, and the program raises the appropriate errors.... so it's is finding the tags inside the file, it just apparently doesn't pick up the value for some reason....
    thanks anyone who can help... this should be simple, but it doesn't want to work for me... bad karma?

    First of all, thanks a million for posting replies to my first two posts on these forums, you don't realize how much you have helped me. I feel bad for not assigning duke dollars so you could get them, so I owe you a few :)
    Anyway, I see what was going on now, my thinking was at first that a Node consisted of a tag and it's value, and now I see that those are each a distinct Node element. So now I see that the enclosed text is itself a separate Node object, so I needed to get the child node of codeNode and then call getNodeValue on it to get the text I was looking for... ah, the life of a programmer...
    anyway, thanks again!!!

  • Unmarshalling a DOM node to an XML file with JAXB

    I'm trying to unmarshall a DOM node to an XML file using JAXB. However I keep receiving a NullPointerException. This only seems to occur when I create the DOM Node from scratch. The stack trace looks like the following:
    java.lang.NullPointerException
            at com.sun.xml.bind.unmarshaller.SAXUnmarshallerHandlerImpl.startElement
    (SAXUnmarshallerHandlerImpl.java:87)
            at com.sun.xml.bind.unmarshaller.DOMScanner.visit(DOMScanner.java:109)
            at com.sun.xml.bind.unmarshaller.DOMScanner.parse(DOMScanner.java:64)
            at com.sun.xml.bind.unmarshaller.UnmarshallerImpl.unmarshal(Unmarshaller
    Impl.java:149)
            at Main.main(Main.java:103)(If I unmarshal an XML file into a DOM node, I can successfully marshall the DOM node out to a new XML file using JAXB without error.)
    Any insight into what I am doing wrong would be greatly appreciated!
    Sample code and XSD follow...
    Sample Code:
    import itemlistsample.*;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.Iterator;
    import java.util.List;
    import javax.xml.bind.JAXBContext;
    import javax.xml.bind.JAXBException;
    import javax.xml.bind.Marshaller;
    import javax.xml.bind.Unmarshaller;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.DocumentBuilder;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.NodeList;
    import org.w3c.dom.Node;
    import org.w3c.dom.Text;
    public class Main
      public static void main(String[] args)
          try
              JAXBContext jc = JAXBContext.newInstance( "itemlistsample" );
              Unmarshaller u = jc.createUnmarshaller();
              * Set up DOM Node Document Object.
              DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
              dbf.setNamespaceAware(true);                   
              DocumentBuilder db = dbf.newDocumentBuilder(); 
              Document doc = db.newDocument();
              System.out.println();
              System.out.println();
              System.out.println("Create a DOM Node and unmarshall to an XML file");
              * Generate elements within DOM document
              Element itemListElt = (Element)doc.createElement("item_list");
              Element itemInfo = (Element)doc.createElement("item_info");
              Element name = (Element)doc.createElement("name");
              Element price = (Element)doc.createElement("price");
              * 3-Ring Binder @ 4.99
              name.appendChild(doc.createTextNode("3-Ring Binder"));
              itemInfo.appendChild(name);
              price.appendChild(doc.createTextNode("4.99"));
              itemInfo.appendChild(price);
              itemListElt.appendChild(itemInfo);
              * Large Paper Clips @ 1.23
              itemInfo = (Element)doc.createElement("item_info");
              name = (Element)doc.createElement("name");
              price = (Element)doc.createElement("price");
              name.appendChild(doc.createTextNode("Large Paper Clips"));
              itemInfo.appendChild(name);
              price.appendChild(doc.createTextNode("1.23"));
              itemInfo.appendChild(price);
              itemListElt.appendChild(itemInfo);
              doc.appendChild(itemListElt);
              * Display DOM document as a sanity check
              itemListElt = doc.getDocumentElement();
              System.out.println(itemListElt.getTagName());
              NodeList nl = itemListElt.getElementsByTagName("item_info");
              traverse("  ", nl.item(0));
              * Use JAXB to unmarshal the DOM document into
              * an instance of the generated JAXB class for
              * the root element.  Stack trace occurs here!
              ItemListType il = (ItemListType)u.unmarshal(doc);
              * Marshal to an XML file
              Marshaller m = jc.createMarshaller();
              m.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE );
              m.marshal( il, new FileOutputStream("item_new.xml") );
          catch (Exception e)
         e.printStackTrace();
      public static void traverse(String indent, Node n)
        if (n != null)
          if (n.getNodeName() != null)
            System.out.println(indent + n.getNodeName());
            traverse(indent + "  ", n.getFirstChild());
          if (n.getNodeValue() != null)
            System.out.println(indent + n.getNodeValue());
          traverse(indent, n.getNextSibling());
    }Sample XSD:
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
         <xsd:element name="item_list" type="ItemListType"/>
         <xsd:complexType name="ItemListType">
              <xsd:sequence>
                   <xsd:element name="item_info" type="ItemInfoType" maxOccurs="unbounded"/>
              </xsd:sequence>
         </xsd:complexType>
         <xsd:complexType name="ItemInfoType">
              <xsd:sequence>
                   <xsd:element name="name" type="xsd:string"/>
                   <xsd:element name="price" type="xsd:double"/>
              </xsd:sequence>
         </xsd:complexType>
    </xsd:schema>

    Modified schema
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <xsd:element name="item_list">     
    <xsd:complexType>          
    <xsd:sequence>               
    <xsd:element ref="item_info" maxOccurs="unbounded"/>     
    </xsd:sequence>
    </xsd:complexType>
    </xsd:element>
    <xsd:element name="item_info">
         <xsd:complexType>          
    <xsd:sequence>               
    <xsd:element name="name" type="xsd:string"/>     
         <xsd:element name="price" type="xsd:double"/>     
         </xsd:sequence>
    </xsd:complexType>
    </xsd:element>
    </xsd:schema>

  • Java.lang.NoSuchMethodError: org.w3c.dom.Element.getTextContent()Ljava/lang

    Hello all,
    I recently developed a app that utilizes a xml file for a database.
    I generated a war file and sent it to a co worker for deployment.
    He gets the following error when he tries to access a jsp
    javax.servlet.ServletException: org.w3c.dom.Element.getTextContent()Ljava/lang/String;
           org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:825)
           org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:758)
           org.apache.jsp.services_jsp._jspService(services_jsp.java:88)
           org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:94)
           javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
           org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:324)
           org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:292)
           org.apache.jasper.servlet.JspServlet.service(JspServlet.java:236)
           javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    root cause
    java.lang.NoSuchMethodError: org.w3c.dom.Element.getTextContent()Ljava/lang/String;
           GSMPackage.GSMManager.getNodeList(GSMManager.java:184)
           GSMPackage.GSMManager.getExistingServices(GSMManager.java:283)
           org.apache.jsp.services_jsp._jspService(services_jsp.java:77)
           org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:94)
           javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
           org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:324)
           org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:292)
           org.apache.jasper.servlet.JspServlet.service(JspServlet.java:236)
           javax.servlet.http.HttpServlet.service(HttpServlet.java:802)I had him check his java version using java -version he has 1.5.
    This method that errors is a 1.5 source error from what I have read.
    Is there something else I can look at?
    Thanks.

    Thanks.
    I thought that the method in question was the getTextContext() method. ?
    org.w3c.dom.Element.getTextContent()Ljava/lang/String
    This is the method that contains the line in question(line 184 is last line):
        public ArrayList getNodeList()
           ArrayList arraylist = new ArrayList();
            try
                String serviceHostPort = null;
                Document document = this.getDocument();
                if(file.exists())
                    NodeList serviceName = document.getElementsByTagName("ServiceName");
                    NodeList serviceHost = document.getElementsByTagName("ServiceHost");
                    NodeList servicePort = document.getElementsByTagName("ServicePort");
                    if(serviceName.getLength() > 0)
                        for(int i=0;i<serviceName.getLength();i++)
                            Element serviceNameElement = (Element) serviceName.item(i); //CREATE THE SERVICE NAME ELEMENT
                            String serviceNameString = serviceNameElement.getTextContent(); //CREATE THE SERVICE NAME CONTENT THIS IS THE LINE IN QUESTION Thanks!

  • Updating XML values with DOM

    Guys,
    I have XML that looks like this:
    <datasheet>
    <row num="1">
    <dept>test</dept>
    <code>test</code>
    <prints>test</prints>
    <origs>test</origs>
    <sf>test</sf>
    <price>test</price>
    <description>test</description>
    </row>
    <row num="2">
    <dept>asdf</dept>
    <code>adad</code>
    <prints>asdf</prints>
    <origs>adf</origs>
    <sf>asdf</sf>
    <price>asdf</price>
    <description>asdf</description>
    </row>
    </datasheet>
    I need to update this info useing DOM, can you help me out. I know how to update single fields but not when they are displayed like this.
              document.getElementsByTagName("department").item(0).getFirstChild().setNodeValue("COLOR2");
    can you help?

    So if it is NULL then we and and then if there is a record we just update like this rigth?
                   NodeList nl=document.getElementsByTagName("row");
                   for(int i=0; i<nl.getLength(); i++){
                        if(((Element)nl.item(i)).getElementsByTagName("dept").item(0).getFirstChild() == null){
                             ((Element)nl.item(i)).getElementsByTagName("dept").item(0).appendChild(document.createTextNode("tagtext"));
                        else {
                             ((Element)nl.item(i)).getElementsByTagName("dept").item(0).getFirstChild().setNodeValue("COLOR2");

  • Air - JavaScript DOM problems

    Dear Air-friends,
    Have a look at this short html:
    <html>
    <head>
    <script type="text/javascript"
    src="AIRAliases.js"></script>
    <script>
    var i = 0;
    var click = function() {
    var a = document.createElement("a");
    a.innerHTML = "click me " + i++;
    a.setAttribute("href", "#");
    a.setAttribute("onclick", "click()");
    document.getElementById("body").replaceChild(a,
    document.getElementsByTagName("a")[0]);
    </script>
    </head>
    <body id="body" onload="click()">
    <a />
    </body>
    </html>
    when I run this using adl something strange happens:
    - I get a "click 0", after I click a "click 1" and ....
    that's it! no continuous "click 2", etc.
    I isolated this problem to this example, but actally I need
    it for context menus in my air application.
    Can someone help? I'm out of ideas.
    Thanks,
    Harrold Korte

    Hi Joe,
    First of all, thanks for your quick reply!
    Maybe I isolated the problem a bit too much. In fact, I'm
    creating context menus using xslt.
    Each time, a new context menu is put under a node called
    <div id="wrap-menu"> containing
    a <ul> of <a>s. It is in these subsequent
    refreshing of the context-menu (produced by xslt)
    where I observed this behaviour (first time ok, second time
    nop). Should I alter each <a> in the produced context-menu
    with addEventListener afterwards?
    I have the feeling that in that case I could didge xslt as
    well. Unfortunatly, I'm a big xslt fan to create
    html output (instead of all these program lines of unpacking
    and DOM manipulation). I'm porting an
    application from JS/PHP to Air because of the file system
    access which is exactly what I was looking for.
    Thanks again,
    Harrold Korte

  • XML DOM

    Below is a method which reads a specific file and uses xml dom to find some values
    public void createDBFromXML(File file){
           try {
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                Document document = db.parse(file);
                document.getDocumentElement().normalize();
                //System.out.println("Root element "+document.getDocumentElement().getNodeName());
                NodeList node;
                //node = document.getElementsByTagName("cat");
                node = document.getElementsByTagName("question");
                final int N = 4;
                Question q;
                for (int i = 0; i < node.getLength(); i++) {
                    Node firstNode = node.item(i);
                    if (firstNode.getNodeType() == Node.ELEMENT_NODE) {
                        Element element = (Element) firstNode;
                        String question;
                        String[] selection;
                        int answer; int category;
                        NodeList qElemntList = element.getElementsByTagName("q");
                        Element qElement = (Element) qElemntList.item(0);
                        NodeList qE = qElement.getChildNodes();
                        //System.out.println("q:"+ ((Node)qE.item(0)).getNodeValue());
                        question = ((Node)qE.item(0)).getNodeValue();
                        selection = new String[N];
                        NodeList c1ElemntList = element.getElementsByTagName("c1");
                        Element c1Element = (Element) c1ElemntList.item(0);
                        NodeList c1E = c1Element.getChildNodes();
                        //System.out.println("q:"+ ((Node)c1E.item(0)).getNodeValue());
                        //Node node = c1E.item(0);
                        selection[0] = ((Node)c1E.item(0)).getNodeValue();
                        System.out.println(node == null);
                        NodeList c2ElemntList = element.getElementsByTagName("c2");
                        Element c2Element = (Element) c2ElemntList.item(0);
                        NodeList c2E = c2Element.getChildNodes();
                        //System.out.println("q:"+ ((Node)c2E.item(0)).getNodeValue());
                        selection[1] = ((Node)c2E.item(0)).getNodeValue();
            } catch (Exception e) {
                e.printStackTrace();
        }the file looks like this:
    <?xml version="1.0" encoding="UTF-8"?>
    <cat>
    <question>
    <q>1 question1</q>
    <c1>choice1</c1>
    <c2>choice2</c2>
    <c3>choice3</c3>
    <c4>choice4</c4>
    <ans>4</ans>
    </question>
    <question>
    <q>1 question2</q><c1>choice1</c1>
    <c2>choice2</c2>
    <c3>choice3</c3>
    <c4>choice4</c4>
    <ans>2</ans>
    </question>I get these errors:
    com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: Invalid byte 2 of 2-byte UTF-8 sequence.
            at com.sun.org.apache.xerces.internal.impl.io.UTF8Reader.invalidByte(UTF8Reader.java:674)
            at com.sun.org.apache.xerces.internal.impl.io.UTF8Reader.read(UTF8Reader.java:362)
            at com.sun.org.apache.xerces.internal.impl.XMLEntityScanner.load(XMLEntityScanner.java:1742)
            at com.sun.org.apache.xerces.internal.impl.XMLEntityScanner.skipChar(XMLEntityScanner.java:1416)
            at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2784)
            at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648)
            at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:510)
            at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:807)
            at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
            at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:107)
            at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:225)
            at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:283)
            at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:208)
            at XmlDB.Database.createDBFromXML(Database.java:34)
            at MainGame.Main.main(Main.java:23)
    BUILD SUCCESSFUL (total time: 2 seconds)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    elias85 wrote:
    how can i read those characters? They are greekThey are in a wrong encoding, so at this point there's nothing that you can do. Make sure that the XML is generated correctly in the first place.
    A valid XML file always has a defined encoding. If nothing is defined in the XML header then it's UTF-8. If your XML file doesn't define anything else and still contains non-UTF-8 encoded data, then it's invalid.

  • XDK DOM 3 implementation doesn't work (i.e ElementEditVAL)

    Hi,
    I want to use XDK DOM 3 implementation to be able to validate my modification against the schema and then save it to file, for that I found that I have to use ElementEditVAL class and canSetXXX methods, but unfortunately none of them is working and always they return UNKNOWN (7) code or null value.
    following are my XML test file and XSD file and at the end the code that I wrote, so I need your help to see why it doesn't work, maybe it is the XSD bug and I don't know about it!
    Thank you in advance for your help
    XML file:
    ?xml version = '1.0' encoding = 'UTF-8'?>
    <config xmlns:xlink="http://www.w3.org/TR/2000/REC-XLINK-20010627" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="mytest.xsd">
    <item name="locked"/>
    </config>
    XSD file:
    <?xml version="1.0" encoding="UTF-8"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
         <xs:complexType name="itemType" mixed="true">
              <xs:attribute name="name" use="required">
                   <xs:simpleType>
                        <xs:restriction base="xs:string">
                             <xs:enumeration value="unlocked"/>
                             <xs:enumeration value="locked"/>
                             <xs:enumeration value="shutdown"/>
                        </xs:restriction>
                   </xs:simpleType>
              </xs:attribute>
         </xs:complexType>
         <xs:element name="config">
              <xs:annotation>
                   <xs:documentation>Comment describing your root element</xs:documentation>
              </xs:annotation>
              <xs:complexType>
                   <xs:sequence>
                        <xs:element name="item" type="itemType"/>
                   </xs:sequence>
              </xs:complexType>
         </xs:element>
    </xs:schema>
    Source code:
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import oracle.xml.parser.v2.DOMParser;
    import oracle.xml.parser.v2.XMLDocument;
    import oracle.xml.parser.v2.XMLElement;
    import oracle.xml.parser.v2.XMLNodeList;
    import org.w3c.dom.NamedNodeMap;
    import org.w3c.dom.validation.ElementEditVAL;
    import java.io.File;
    public class forum{
         static XMLDocument document;
         static final String schemaSource = "C:/cmt/ServerSolarisTest/config/mytest.xsd";     
         static final String JAXP_SCHEMA_SOURCE ="http://java.sun.com/xml/jaxp/properties/schemaSource";     
         static final String JAXP_SCHEMA_LANGUAGE ="http://java.sun.com/xml/jaxp/properties/schemaLanguage";
         static final String W3C_XML_SCHEMA ="http://www.w3.org/2001/XMLSchema";
         public static void main(String[] args) {
              if(args.length !=1){
                   System.err.println("Please enter the file name");
                   System.exit(1);
              }//if
              System.out.println("Start parsing.....");
              try{
    //               Create URL String from incoming file
         String url = "file:" + new File(args[0]).getAbsolutePath();               
         String schemaurl = "file:" + new File("C:/cmt/ServerSolarisTest/config/mytest.xsd").getAbsolutePath();
                   DOMParser parser = new DOMParser();
    // Set parser options
    parser.setErrorStream(System.err);
    parser.setValidationMode(DOMParser.SCHEMA_VALIDATION);
    parser.showWarnings(true);
    parser.setXMLSchema(schemaurl);
    //               Parser the incoming file (URL)               
    parser.parse(url);
                   document = parser.getDocument();
                   XMLElement root = (XMLElement)(document.getDocumentElement());
                   XMLElement Current;
                   NamedNodeMap attribs;
                   XMLNodeList nlist = (XMLNodeList)document.getElementsByTagName("*");
                   String nodeName;
                   for(int i = 0; i<nlist.getLength(); i++)
                        attribs = nlist.item(i).getAttributes();
                        Current = (XMLElement)nlist.item(i);
                        ElementEditVAL elval = (ElementEditVAL)Current;
                        //See if Element is item
                        if(Current.getNodeName().equals("item"))
                             for(int j = 0; j<attribs.getLength(); j++)
                                  nodeName = attribs.item(j).getNodeName();
                                  if(nodeName.equalsIgnoreCase("name"))
                                       if(elval.canSetAttribute(nodeName, "unlockedsdf") == ElementEditVAL.VAL_TRUE)
                                            System.out.println("Valid attribute value");
                                            Current.setAttribute(nodeName, "unlockedsdf");
                                       else
                                            System.out.println("Invalid attribute value");
                                       if(elval.canSetAttribute(nodeName, "locked") == ElementEditVAL.VAL_TRUE)
                                            System.out.println("Valid attribute value");
                                            Current.setAttribute(nodeName, "unlockedsdf");
                                       else
                                            System.out.println("Invalid attribute value");
                   //write
                   TransformerFactory tFactory =
    TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer();
    DOMSource source = new DOMSource(document);
    StreamResult result = new StreamResult(new File(args[0]));
    transformer.transform(source, result);                              
              }catch(Exception e){
                   e.printStackTrace();
         }//main     
    }//DomEcho2

    Using DOM 3.0 Validation Techniques with XDK 10g
    http://www.devx.com/Java/Article/31221

  • 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);
    }

  • DOM Help Needed ! Please

    Please help me understand how to walk a DOM tree and extract the node values -
    here's the code I'm using and the XML file -
    SiteID is the only value I've been able to obtain -
    Thanks
                   Document document = builder.parse(file2parse);
                   Node rootNode = document.getDocumentElement();
                   NodeList SiteIDlist = document.getElementsByTagName("Site");
                   for (int i=0; i < SiteIDlist.getLength(); i++) {
                        Node thisSiteNode = SiteIDlist.item(i);
                        for (Node child = thisSiteNode.getFirstChild();
                             child != null;
                             child = child.getNextSibling()) {
                             SiteID = thisSiteNode.getAttributes().getNamedItem("Name").getNodeValue();
    //                         String ItemCode = thisSiteNode.getNextSibling().getNodeValue() + i;                    
    //                         String DomainName = "ServerMatrix" + i;      
    //                         thisSiteNode.getNextSibling().getNodeValue() + 1;
    //                         String SiteStorageAlloc = thisSiteNode.getNextSibling().getNodeValue();
    //                         String StorageUsed = thisSiteNode.getNextSibling().getNodeValue();
                        // Append to SQLServer Database
                        stmt.executeUpdate(
                        "INSERT INTO FTHSite " +
                        "(SiteID, ItemCode, ReSellerID, SiteCreateDate) " +     
                        "VALUES ('" + SiteID + "'," +
                        "'FTHItem'," +
                        "'Server Matrix'," +
                        "'03/31/2004'" + ");"
                   thisSiteNode.getNextSibling();
                   } // end for
    Here's what the XML looks like:
    <?xml version="1.0" encoding="UTF-8"?>
    <FTHSites>
    <Site Name="C1001">
    <ItemCode>Item Code is Null</ItemCode>
    <DomainName>DomainName</DomainName>
    <SiteStorageAlloc>7.0</SiteStorageAlloc>
    <StorageUsed>SiteStorageUsed</StorageUsed>
    <ActiveStatus>N</ActiveStatus>
    </FTHSites>

    Try this:
    Document document = builder.parse(file2parse);
    NodeList siteIDlist = document.getElementsByTagName("Site");
    for (int i = 0; i < siteIDlist.getLength(); i++) {
        Node thisSiteNode = siteIDlist.item(i);                       
        String siteID = thisSiteNode.getAttributes().getNamedItem("Name").getNodeValue();
        String itemCode = null;
        String domainName = null;
        String siteStorageAlloc = null;
        String storageUsed = null;
        String activeStatus = null;
        for (Node child = thisSiteNode.getFirstChild(); child != null; child = child.getNextSibling()) {
            if (child.getNodeType() == Node.ELEMENT_NODE ) {
                String name = child.getNodeName();
                if (name.equalsIgnoreCase("ItemCode"))
                    itemCode = child.getFirstChild().getNodeValue();
                else if (name.equalsIgnoreCase("DomainName"))
                    domainName = child.getFirstChild().getNodeValue();
                else if (name.equalsIgnoreCase("SiteStorageAlloc"))
                    siteStorageAlloc = child.getFirstChild().getNodeValue();
                else if (name.equalsIgnoreCase("StorageUsed"))
                    storageUsed = child.getFirstChild().getNodeValue();
                else if (name.equalsIgnoreCase("ActiveStatus"))
                    activeStatus = child.getFirstChild().getNodeValue();
        // Append to SQLServer Database
        stmt.executeUpdate(
            "INSERT INTO FTHSite " +
            "(SiteID, ItemCode, ReSellerID, SiteCreateDate) " +
            "VALUES ('" + siteID + "'," +
            "'" + itemCode + "'," +
            "'Server Matrix'," +
            "'03/31/2004'" + ");"
    } // end forPlease next time paste your code between code tags exactly like this:
    &#91;code&#93;
    your code
    &#91;/code&#93;
    Thank you

Maybe you are looking for