This discussion is archived
6 Replies Latest reply: Sep 28, 2007 10:01 AM by 807605 RSS

count elements in xml file

807605 Newbie
Currently Being Moderated
Hi,

I need some help.

I would like to write a java code which reads an xml file (based on a.xsd), parse it, count the number of elements and compare those elements with another schema (b.xsd) file to check whether they are exists or not. if the element is doesn't exist, i would like to through an error.

Can some one help me on this?

thanks in advance
  • 1. Re: count elements in xml file
    807605 Newbie
    Currently Being Moderated
    I suggest you post the work you have already done and/or specific questions you have related to this problem.
    Questions such as "here is a problem, what do I do?" are too vague and unlikely to get quality responses.
  • 2. Re: count elements in xml file
    807605 Newbie
    Currently Being Moderated
    What I can do to help is to suggest the right technology. And that I will. Look at XMLBeans

    http://www.onjava.com/pub/a/onjava/2004/07/28/XMLBeans.html
  • 3. Re: count elements in xml file
    DrClap Expert
    Currently Being Moderated
    And why would you like to write that in Java?

    Part of your description sounds rather as if you want to validate the XML against a schema. That's built into most XML parsers these days, I certainly wouldn't advocate beginners to do something so complex. As for the counting of elements, a simple XSLT program would be preferable to writing specific code in Java.
  • 4. Re: count elements in xml file
    807605 Newbie
    Currently Being Moderated
    ok here is the code which is parsing the xml file. the missing thing is counting the elements and comparing with another .xsd file.

    please keep in mind that input.xml file is based on one schema (aaa.xsd)but doing all counting, parsing etc i would like to compare elements with another schema (bbb.xsd) for existence.

    /*
    * ParseXMLFile.java
    *
    *
    */

    import java.io.*;
    import org.w3c.dom.*;
    import org.xml.sax.*;
    import javax.xml.parsers.*;
    import javax.xml.transform.*;
    import javax.xml.transform.dom.*;
    import javax.xml.transform.stream.*;

    /** This class represents short example how to parse XML file,
    * get XML nodes values and its values.<br><br>
    * It implements method to save XML document to XML file too
    *
    */
    public class ParseXMLFile {

    private final static String xmlFileName = "C:/example.xml";
    private final static String targetFileName = "C:/result.xml";

    /** Creates a new instance of ParseXMLFile */
    public ParseXMLFile() {
    // parse XML file -> XML document will be build
    Document doc = parseFile(xmlFileName);
    // get root node of xml tree structure
    Node root = doc.getDocumentElement();
    // write node and its child nodes into System.out
    System.out.println("Statemend of XML document...");
    writeDocumentToOutput(root,0);
    System.out.println("... end of statement");
    // write Document into XML file
    saveXMLDocument(targetFileName, doc);
    }

    /** Returns element value
    * @param elem element (it is XML tag)
    * @return Element value otherwise empty String
    */
    public final static String getElementValue( Node elem ) {
    Node kid;
    if( elem != null){
    if (elem.hasChildNodes()){
    for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
    if( kid.getNodeType() == Node.TEXT_NODE ){
    return kid.getNodeValue();
    }
    }
    }
    }
    return "";
    }

    private String getIndentSpaces(int indent) {
    StringBuffer buffer = new StringBuffer();
    for (int i = 0; i < indent; i++) {
    buffer.append(" ");
    }
    return buffer.toString();
    }

    /** Writes node and all child nodes into System.out
    * @param node XML node from from XML tree wrom which will output statement start
    * @param indent number of spaces used to indent output
    */
    public void writeDocumentToOutput(Node node,int indent) {
    // get element name
    String nodeName = node.getNodeName();
    // get element value
    String nodeValue = getElementValue(node);
    // get attributes of element
    NamedNodeMap attributes = node.getAttributes();
    System.out.println(getIndentSpaces(indent) + "NodeName: " + nodeName + ", NodeValue: " + nodeValue);
    for (int i = 0; i < attributes.getLength(); i++) {
    Node attribute = attributes.item(i);
    System.out.println(getIndentSpaces(indent + 2) + "AttributeName: " + attribute.getNodeName() + ", attributeValue: " + attribute.getNodeValue());
    }
    // write all child nodes recursively
    NodeList children = node.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
    Node child = children.item(i);
    if (child.getNodeType() == Node.ELEMENT_NODE) {
    writeDocumentToOutput(child,indent + 2);
    }
    }
    }

    /** Saves XML Document into XML file.
    * @param fileName XML file name
    * @param doc XML document to save
    * @return <B>true</B> if method success <B>false</B> otherwise
    */
    public boolean saveXMLDocument(String fileName, Document doc) {
    System.out.println("Saving XML file... " + fileName);
    // open output stream where XML Document will be saved
    File xmlOutputFile = new File(fileName);
    FileOutputStream fos;
    Transformer transformer;
    try {
    fos = new FileOutputStream(xmlOutputFile);
    }
    catch (FileNotFoundException e) {
    System.out.println("Error occured: " + e.getMessage());
    return false;
    }
    // Use a Transformer for output
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    try {
    transformer = transformerFactory.newTransformer();
    }
    catch (TransformerConfigurationException e) {
    System.out.println("Transformer configuration error: " + e.getMessage());
    return false;
    }
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(fos);
    // transform source into result will do save
    try {
    transformer.transform(source, result);
    }
    catch (TransformerException e) {
    System.out.println("Error transform: " + e.getMessage());
    }
    System.out.println("XML file saved.");
    return true;
    }

    /** Parses XML file and returns XML document.
    * @param fileName XML file to parse
    * @return XML document or <B>null</B> if error occured
    */
    public Document parseFile(String fileName) {
    System.out.println("Parsing XML file... " + fileName);
    DocumentBuilder docBuilder;
    Document doc = null;
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    docBuilderFactory.setIgnoringElementContentWhitespace(true);
    try {
    docBuilder = docBuilderFactory.newDocumentBuilder();
    }
    catch (ParserConfigurationException e) {
    System.out.println("Wrong parser configuration: " + e.getMessage());
    return null;
    }
    File sourceFile = new File(fileName);
    try {
    doc = docBuilder.parse(sourceFile);
    }
    catch (SAXException e) {
    System.out.println("Wrong XML file structure: " + e.getMessage());
    return null;
    }
    catch (IOException e) {
    System.out.println("Could not read source file: " + e.getMessage());
    }
    System.out.println("XML file parsed");
    return doc;
    }

    /** Starts XML parsing example
    * @param args the command line arguments
    */
    public static void main(String[] args) {
    new ParseXMLFile();
    }

    }
  • 5. Re: count elements in xml file
    DrClap Expert
    Currently Being Moderated
    Wow. Way too much code.

    For example, what's all that business about identifying text nodes and indenting things? Nothing to do with counting elements.

    And there's a whole lot of code in there about attributes, and some code that writes out XML. None of it has anything to do with your requirements.

    If you want to validate your XML document against a specific schema, it's possible to do that just by telling the parser to do it. I don't recall how but you should be able to google some code for that.
  • 6. Re: count elements in xml file
    807605 Newbie
    Currently Being Moderated
    I am able to parse the xml. any idea which method i should use to count the elements after parsing?

    thanks