Xml file parse  event base

hello all,
i am learning xml file with sap help sample. I have a FM, that change xml-file into if_ixml_parser, but when i wrote the xml " <person status="retired">Walt Whitman</person>" and debug it.
event_sub was 312, <b>event was always initial</b>.
data: event     type ref to if_ixml_event,
        event_sub type i.
let the parser know which events I am interested in
event_sub = if_ixml_event=>co_event_element_pre2 +
            if_ixml_event=>co_event_element_post.
parser->set_event_subscription( events = event_sub ).
do.
  event = parser->parse_event( ).
  if event is initial.
    exit. ' either end reached or error (check below)
  endif.
  data: str type string.
  case event->get_type( ).
    when if_ixml_event~co_event_element_pre2.
      str = event->get_name( ).
      write: '<' str '>'.
    when if_ixml_event~co_event_text_post.
      str = event->get_value( ).
      write: str.
  endcase.
enddo.
Thanks for Request.
<a href="http://help.sap.com/saphelp_nwmobile71/helpdata/de/47/b5413acdb62f70e10000000a114084/frameset.htm">sap library - Parsing an XML document event-based</a>
Best regards
Shuo

Hi,
     reference link:
http://help.sap.com/saphelp_nw04/helpdata/en/fd/9d7348389211d596a200a0c94260a5/frameset.htm
http://help.sap.com/saphelp_nw04/helpdata/en/bb/576670dca511d4990b00508b6b8b11/content.htm
Please see the PDF document which tells you how to develop with KM API's
https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/aef1a890-0201-0010-6faf-8fa094808653
Regards

Similar Messages

  • XML file parse issue

    I have a requirement to print <attribute-override> and <column> in a spreadsheet.
    My xml file is as
    <?xml version="1.0" encoding="UTF-8"?>
    <entity-mappings xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/orm" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.eclipse.org/eclipselink/xsds/persistence/orm http://www.eclipse.org/eclipselink/xsds/eclipselink_orm_2_4.xsd">
      <entity class="com.ofss.fc.domain.account.entity.accountcreditmatrix.CreditMetricDetails">
        <table name="FLX_AC_ACCT_CREDIT_MATRIX_DTLS"/>
        <attributes>
          <embedded-id attribute-type="com.ofss.fc.domain.account.entity.accountcreditmatrix.CreditMetricDetailsKey" name="key">
            <attribute-override name="accountId">
              <column name="ACCOUNT_ID"/>
            </attribute-override>
            <attribute-override name="accountType">
              <column name="ACCOUNT_TYPE"/>
            </attribute-override>
            <attribute-override name="effectiveDate">
              <column name="EFFECTIVE_DATE"/>
            </attribute-override>
            <attribute-override name="matrixIdvalue">
              <column name="MATRIX_ID_VALUE"/>
            </attribute-override>
            <attribute-override name="classification">
              <column name="Classification"/>
            </attribute-override>
          </embedded-id>
          <embedded attribute-type="com.ofss.fc.domain.account.entity.accountcreditmatrix.CreditMetric" name="creditMetric">
            <attribute-override name="metricType">
              <column name="METRIC_TYPE" unique="false"/>
            </attribute-override>
            <attribute-override name="metricValue">
              <column name="METRIC_VALUE" unique="false"/>
            </attribute-override>
          </embedded>
          <embedded attribute-type="com.ofss.fc.domain.account.entity.accountcreditmatrix.RiskScore" name="riskScore">
            <attribute-override name="scoreType">
              <column name="SCORE_TYPE" unique="false"/>
            </attribute-override>
            <attribute-override name="otherScoreType">
              <column name="OTHER_SCORE_TYPE" unique="false"/>
            </attribute-override>
            <attribute-override name="scoreCardExternalReferenceNo">
              <column name="SCORE_EXTR_REF_NO" unique="false"/>
            </attribute-override>
            <attribute-override name="ratingModel">
              <column name="RATING_MODEL" unique="false"/>
            </attribute-override>
            <attribute-override name="ratingStatus">
              <column name="RATING_STATUS" unique="false"/>
            </attribute-override>
            <attribute-override name="riskGrade">
              <column name="RISK_GRADE" unique="false"/>
            </attribute-override>
            <attribute-override name="scoreCardIndex">
              <column name="SCORE_CARD_INDEX" unique="false"/>
            </attribute-override>
            <attribute-override name="score">
              <column name="SCORE" unique="false"/>
            </attribute-override>
          </embedded>
        </attributes>
      </entity>
    </entity-mappings>
    I have managed to write the code as
    package xmlexcel;
    import org.apache.poi.hssf.usermodel.*;
    import java.util.ArrayList;
    import java.awt.List;
    import java.io.*;
    import java.util.ArrayList;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import org.xml.sax.SAXException;
    import org.apache.poi.hssf.usermodel.HSSFCell;
    import org.apache.poi.hssf.usermodel.HSSFRow;
    import org.apache.poi.hssf.usermodel.HSSFSheet;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    public class XMLconvertExcel {
      private static File xmlDocument;
        private static NodeList e;
        int a;
      public void generateExcel(File xmlDocument) {
      try {
      HSSFWorkbook wb = new HSSFWorkbook();
      HSSFSheet spreadSheet = wb.createSheet("spreadSheet");
      spreadSheet.setColumnWidth((short)0,(short) (256*25));
      spreadSheet.setColumnWidth((short)1,(short) (256*25));
      spreadSheet.setColumnWidth((short)2,(short) (256*25));
      spreadSheet.setColumnWidth((short)3,(short) (256*25));
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      DocumentBuilder builder = factory.newDocumentBuilder();
      Document document = builder.parse(xmlDocument);
      NodeList nList = document.getElementsByTagName("attributes");
      document.getDocumentElement().normalize();
      //a=nodelist.getLength();
      //e = printStackTrace();
      //System.out.println("I am here " +e);
             System.out.println("Root element :" + document.getDocumentElement().getNodeName() + " nlist length  " +nList.getLength());
             System.out.println("Node Type :" + document.getDocumentElement().getNodeType());
      HSSFRow row = spreadSheet.createRow(0);
      HSSFCell cell = row.createCell((short)0);
      cell.setCellValue("Entity");
      cell = row.createCell((short)1);
      cell.setCellValue("Table");
      cell = row.createCell((short)2);
      cell.setCellValue("Attribute");
      cell = row.createCell((short)3);
      cell.setCellValue("Column");
      HSSFRow row1 = spreadSheet.createRow(1);
      HSSFRow row2 = spreadSheet.createRow(2);
      HSSFRow row3 = spreadSheet.createRow(3);
      for (int i = 0; i < nList.getLength(); i++) {
      Node nNode = nList.item(i);
                 System.out.println("\nCurrent Element :"    + nNode.getNodeName());
                 switch {
      case 0:
      //cell = row1.createCell((short)0);
      //cell.setCellValue("Attribute");
      //trying from http://architects.dzone.com/articles/parsing-xml-using-dom-sax-and
      cell = row1.createCell((short) 2);
                    cell.setCellValue(((Element) (nList.item(0)))
                       .getElementsByTagName("attribute-override").item(0)
                       .getFirstChild().getNodeValue());
      break;
      case 1:
      //cell = row1.createCell((short)1);
      //cell.setCellValue("Table");
      cell = row1.createCell((short) 3);
      cell.setCellValue(((Element) (nList.item(0)))
      .getElementsByTagName("column").item(0)
      .getFirstChild().getNodeValue());
      break;
      case 2:
      cell = row1.createCell((short)2);
      cell.setCellValue("Attribute");
      cell = row1.createCell((short) 2);
      cell.setCellValue(((Element) (nodelist.item(2)))
      .getElementsByTagName("attribute-override").item(0)
      .getFirstChild().getNodeValue());
      cell = row1.createCell((short)3);
      cell.setCellValue("Column");
      cell = row1.createCell((short) 3);
      cell.setCellValue(((Element) (nodelist.item(3)))
      .getElementsByTagName("column").item(0)
      .getFirstChild().getNodeValue());
      break;
      default:
      break;
      //wb.write(arg1.getOutputPayload().getOutputStream());
      //Outputting to Excel spreadsheet
      FileOutputStream output = new FileOutputStream(new File("C:\\java_training\\com\\XMLtoExcel\\ormaccount.xls"));
             wb.write(output);
             output.flush();
             output.close();
      } catch (IOException e) {
      System.out.println("IOException " + e.getMessage());
      } catch (ParserConfigurationException e) {
      System.out.println("ParserConfigurationException " +e.getMessage());
      }catch (SAXException e) {
      System.out.println("SAXException " +e.getMessage());
      private String printStackTrace() {
      // TODO Auto-generated method stub
      return null;
      * @param args
      public static void main(String[] args) {
      File xmlDocument = new File("C:\\java_training\\com\\XMLtoExcel\\AccountCreditMatrixDetails.orm.xml");
      XMLconvertExcel excel = new XMLconvertExcel();
      excel.generateExcel(xmlDocument);
    Both the tags are not getting printed in separate columns.
    I have looked at
    http://www.javaworld.com/article/2076189/enterprise-java/book-excerpt--converting-xml-to-spreadsheet--and-vice-versa.html
    http://scn.sap.com/thread/3224533
    http://www.tutorialspoint.com/java_xml/java_dom_parse_document.htm
    The above URL shows example of simple xml.
    Please can I get assistance.

    I too received this error as I tried to run my first Windows 8.1 deployment. Per another post I commented out this line
    <IEWelcomeMsg>false</IEWelcomeMsg>
    from the IE section of the unattend.xml. I was then able to run my deployment. I do not see this line in your posting though.
    I referenced this link even though it was for Windows 7.
    http://social.technet.microsoft.com/Forums/en-US/c41a2b69-a591-4cd3-86ab-6a0f8a73b858/getting-windows-could-not-parse-or-process-the-unattend-answer-file-for-pass-specialize-with?forum=mdt
    Hope this helps someone.
    JayTheTech
    To clarify, I edited the unattend.xml file from from Deployment Share, not C:\Windows\Panther.
    DS\control\task sequence ID\unattend.xml
    JayTheTech

  • JSP XML file parsing XSLT using Xalan

    Hi all
    I have created an XML file "view_campaign.xml" using JSP as shown in a code below and i wanna know how i should proceed to parse the XML file and so i can display this XML as the XSLT file i created.
    <%@ page import="java.sql.*" %>
    <%@ page import="java.io.*" %>
    <%
    // Identify a carriage return character for each output line
    int iLf = 10;
    char cLf = (char)iLf;
    // Create a new empty binary file, which will content XML output
    File outputFile = new File("C:\\WebContent\\view_campaigns.xml");
    //outputFile.createNewFile();
    FileWriter outfile = new FileWriter(outputFile);
    // the header for XML file
    outfile.write("<?xml version='1.0' encoding='ISO-8859-1'?>"+cLf);
    try {
         // Define connection string and make a connection to database
         //DriverManager.registerDriver (new org.apache.derby.jdbc.ClientDriver());
         Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1527/sample","app","app");
         Statement stat = conn.createStatement();
         // Create a recordset
         ResultSet rset = stat.executeQuery("Select * From campagn");
         // Expecting at least one record
         if( !rset.next() ) {
              throw new IllegalArgumentException("No data found for the campaigns table");
         outfile.write("<campaigns>"+cLf);
         outfile.write("<campaign>"+cLf);
         outfile.write("<campaign_id>" + rset.getString("campagn_id") +"</campaign_id>"+cLf);
         outfile.write("<campaign_name>" + rset.getString("campagn_name") +"</campaign_name>"+cLf);
         outfile.write("<campaign_type>" + rset.getString("campagn_type") +"</campaign_type>"+cLf);
         outfile.write("<client>" + rset.getString("client_name") +"</client>"+cLf);
         outfile.write("<positions>" + rset.getString("positions_nbr") +"</positions>"+cLf);
         outfile.write("<begin>" + rset.getString("campagn_beginning_date") +"</begin>"+cLf);
         outfile.write("<close>" + rset.getString("campagn_ending_date") +"</close>"+cLf);
         outfile.write("</campaign>"+cLf);
         // Parse our recordset
    // Parse our recordset
         while(rset.next()) {
              outfile.write("<campaign>"+cLf);
              outfile.write("<campaign_id>" + rset.getString("campagn_id") +"</campaign_id>"+cLf);
              outfile.write("<campaign_name>" + rset.getString("campagn_name") +"</campaign_name>"+cLf);
              outfile.write("<campaign_type>" + rset.getString("campagn_type") +"</campaign_type>"+cLf);
              outfile.write("<client>" + rset.getString("client_name") +"</client>"+cLf);
              outfile.write("<positions>" + rset.getString("positions_nbr") +"</positions>"+cLf);
              outfile.write("<begin>" + rset.getString("campagn_beginning_date") +"</begin>"+cLf);
              outfile.write("<close>" + rset.getString("campagn_ending_date") +"</close>"+cLf);
              outfile.write("</campaign>"+cLf);
         outfile.write("</campaigns>"+cLf);
         // Everything must be closed
         rset.close();
         stat.close();
         conn.close();
         outfile.close();
    catch( Exception er ) {
    %>////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    this is my .XSL file
    <?xml version="1.0" encoding="iso-8859-1" ?>
    - <!--  DWXMLSource="view_campaigns.xml"
      -->
      <!DOCTYPE xsl:stylesheet (View Source for full doctype...)>
    - <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
      <xsl:output method="html" encoding="iso-8859-1" doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN" doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" />
    - <xsl:template match="/">
    - <html xmlns="http://www.w3.org/1999/xhtml">
    - <head>
      <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
      <title>Gestion des campagnes</title>
      </head>
    - <body>
      Gestion des campagnes
    - <table border="1">
    - <tr bgcolor="#9acd32">
      <th align="left">Code</th>
      <th align="left">Nom</th>
      <th align="left">Type</th>
      <th align="left">Client</th>
      <th align="left">Nombre de positions</th>
      <th align="left">Date d'ouverture</th>
      <th align="left">Date de cl�ture</th>
      </tr>
    - <xsl:for-each select="campaigns/campaign">
    - <tr>
    - <td>
      <xsl:value-of select="campaign_id" />
      </td>
    - <td>
      <xsl:value-of select="campaign_name" />
      </td>
    - <td>
      <xsl:value-of select="campaign_type" />
      </td>
    - <td>
      <xsl:value-of select="client" />
      </td>
    - <td>
      <xsl:value-of select="positions" />
      </td>
    - <td>
      <xsl:value-of select="begin" />
      </td>
    - <td>
      <xsl:value-of select="close" />
      </td>
      </tr>
      </xsl:for-each>
      </table>
      </body>
      </html>
      </xsl:template>
      </xsl:stylesheet>I would be greatful that u answer my question what i should do have any exemple case study.

    Hi,
    Try this code
    JspWriter out = pageContext.getOut(); // Get JSP output writter
          javax.xml.transform.TransformerFactory tFactory = javax.xml.transform.TransformerFactory.newInstance(); //Instantiate a TransformerFactory.           
          String realPath = "c:/applyXsl.xsl";
          java.io.File file = new java.io.File(realPath); // crearte a file object for given XSL.
          // Use the TransformerFactory to process the stylesheet Source and  generate a Transformer.           
          javax.xml.transform.Transformer transformer = tFactory.newTransformer(new javax.xml.transform.stream.StreamSource(file));
          java.io.StringReader inputStream = new java.io.StringReader("c:/xmlFile.xml"); // create an input stream for given XML doc
          java.io.ByteArrayOutputStream obj = new java.io.ByteArrayOutputStream(); // Create an output stream for XSL applied XML doc.
          // 3. Use the Transformer to transform an XML Source and send the output to a Result object.
          transformer.transform(new javax.xml.transform.stream.StreamSource(inputStream), new javax.xml.transform.stream.StreamResult(obj));
          String outputString = obj.toString(); // get the XSL applied applied XML document for print
          out.println(outputString); // print the XSL applied XML in to JSP.
    however you need xercesImpl.jar  and xml-apis.jar files  to run this program.
    Regards,
    Ananth.P

  • XML file parser

    Is there some Java package which able me to parse a XML file ?
    a method like as:
    public Enumeration parseXML(File file);
    ?????????

    Yes,
    You've the package named: javax.xml.parsers
    And you've a class called: javax.xml.parsers.SAXParser
    To know more about parsers, java.sun.com/xml
    There are many different parsers available based on SAX (Simple API for XML Parsing) and DOM!
    -RK.

  • Loading JEditorPane from an XML file parsed by

    an XSL translator.
    the JEditorPane setPage needs a URL, I'm wondering if there is anyway way to have the XSL tool write directly to the JEditorPane?

    If the XSL translator is producing HTML, and it can be run at the command line and send its output to stdout (as many of them can), then there's an approach to a solution.
    JEditorPane has a read() method that takes an InputStream as a parameter. You could use Runtime.getRuntime().exec() to run the XSL translator, then use getInputStream() from the resulting Process object to capture its output, and give that InputStream to JEditorPane.read().
    That's an outline of what I would try. Runtime.exec() is a notoriously irritating thing to get working, so it might fail, but you could give it a try.

  • How to parse a xml file within a WLST script

    Hi all,
    I'm using ALSB2.6 and I'm writing a WLST script that should read config info from a xml file and create an ALSB prj.
    I got an error when I call:
    xmldoc = minidom.parse(sock).documentElement
    The code:
    print '#### IPEventConfigFile: ', IPEventConfigFile
    IPEventConfig = loadXML(IPEventConfigFile)
    where
    def loadXML(source):
    sock = open(source)
    xmldoc = minidom.parse(sock).documentElement
    sock.close()
    return xmldoc
    The error:
    [java] #### IPEventConfigFile: /products/software/terraferma/release3/EventBus/repository/events/DummyEvent/resource/DummyEvent-IPEventConfig.xml
    [java] ===============================================================
    [java] Unexpected error: exceptions.AttributeError
    [java] ===============================================================
    [java] No stack trace available.
    [java] Unexpected error: exceptions.AttributeError
    [java] No stack trace available.
    [java] Problem invoking WLST - Traceback (innermost last):
    [java] File "/products/software/terraferma/release3/EventBus/scripts/cloning.py", line 198, in ?
    [java] File "/products/software/terraferma/release3/EventBus/scripts/cloning.py", line 102, in cloning
    [java] File "/products/software/terraferma/release3/EventBus/scripts/cloning.py", line 178, in loadXML
    [java] File "Lib/xml/dom/minidom.py", line 908, in parse
    [java] File "Lib/xml/dom/minidom.py", line 900, in _doparse
    [java] File "Lib/xml/dom/pulldom.py", line 251, in getEvent
    [java] AttributeError: feed
    Line 178 is:
    xmldoc = minidom.parse(sock).documentElement
    I'm trying to understand where I'm wrong.
    Thanks in advance
    ferp

    Using the SAXParser in JAXP the parsing of the XML file is event driven.
    Instantiate the parser:
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser parser = factory.newSAXParser();
    InputSource is = new InputSource(new FileReader(theXML));call the parse method:
    parser.parse(is, this);The following events are fired as the parser works through the XML public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws org.xml.sax.SAXException
    public void endElement(String namespaceURI, String localName, String qName) throws org.xml.sax.SAXException
    characters(char[] ch, int start, int length)etc.
    You write what you want within each of these sections to handle the structure of your data. Keep in mind SAX is useful only when you know the structure of your XML.

  • How to parse a XML file

    I am a new learner to XML & JAVA,I dont't know how to parse the XML file using JAXP,Who can tell me,Who can write an Example?
    thx
    Best Regards.

    Using the SAXParser in JAXP the parsing of the XML file is event driven.
    Instantiate the parser:
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser parser = factory.newSAXParser();
    InputSource is = new InputSource(new FileReader(theXML));call the parse method:
    parser.parse(is, this);The following events are fired as the parser works through the XML public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws org.xml.sax.SAXException
    public void endElement(String namespaceURI, String localName, String qName) throws org.xml.sax.SAXException
    characters(char[] ch, int start, int length)etc.
    You write what you want within each of these sections to handle the structure of your data. Keep in mind SAX is useful only when you know the structure of your XML.

  • "character conversion error" while parsing xml files

    Hello,
    I'm trying to parse MusicXML (Recordare) files, but I'm getting an exception.
    I'm using the SAX parser (javax.xml.parsers.SAXParser).
    Here is the code I use to instantiate it:
    final javax.xml.parsers.SAXParserFactory saxParserFactory = javax.xml.parsers.SAXParserFactory.newInstance();
    final javax.xml.parsers.SAXParser saxParser = saxParserFactory.newSAXParser();
    final org.xml.sax.XMLReader parser = saxParser.getXMLReader();
    I'm using my own handler, but I get the same exception even if I use org.xml.sax.helpers.DefaultHandler.
    The error I get is:
    Character conversion error: "Illegal ASCII character, 0xc2" (line number may be too low).
    The first few lines of my xml files look like this:
    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <!DOCTYPE score-partwise
    PUBLIC "-//Recordare//DTD MusicXML 0.6 Partwise//EN"
    "http://www.musicxml.org/dtds/partwise.dtd">
    <score-partwise>
    [...etc...]
    If I delete the <!DOCTYPE ...> line, then I don't get the exception anymore. But the MusicXML files I get (from some other program) always contain this line, and it would be quite some work to delete them from every file manually.
    So does anyone know if there is a way to avoid deleting that line in every file, while still being able to parse the xml files without exceptions?
    Or maybe does anyone know what the exact cause of the exception is? (because I don't know what exactly causes it)
    Thank you in advance.
    Greetz,
    Jipo

    So does anyone know if there is a way to avoid
    deleting that line in every file, while still being
    able to parse the xml files without exceptions?ok this is side-stepping the real problem but I've used this code to filterout DTD references for other reasons   public static InputStream filterOutDTDRef(InputStream in) throws IOException {
          BufferedReader iniReader = new BufferedReader(new InputStreamReader(in));
          StringBuffer newXML = new StringBuffer();
          for(String line = iniReader.readLine(); line!=null; line = iniReader.readLine())
             newXML.append(line+"\n");
          in.close();
          int s = newXML.indexOf("<!DOCTYPE ");
          if(s!=-1)
             newXML.replace(s,newXML.indexOf(">",s)+1,"");
          return new ByteArrayInputStream(newXML.toString().getBytes());
       }and it actually speeds up the parsing phase too (since the DTD ref.s were on the web and the XML standard mandates that there is a fetch for each xml file parsed..)
    you can feed the above into the InputSource constructor that takes an InputStream argument.
    Now for the real problem... 0xc2 is "LATIN CAPITAL LETTER A WITH CIRCUMFLEX" according to a unicode chart - which is not an ASCII character (as the error message correctly reports). I'm not sure why the file is being parsed as ASCII though? You could try parsing in a FileReader to the inputsource and hope it picks up the default character encoding of your system, and that that character encoding matches the file. Or you could try passing in a FileReader constructed with a explicit character encoding (eg "UTF8") and see if that does the trick?
    asjf

  • How to compare after parsing xml file

    Hi,
    following code, parse the input.xml file, counts how many nodes are there and writes the node name and its value on screen.
    1) i am having trouble writing only node name into another file instead of writing to screen.
    2) after parsing, i like to compare each node name with another .xsd file for existence.
    Please keep in mind that, input.xml is based on some other .xsd and after parsing i have comparing its tag with another .xsd
    Need you help guys.
    thanks
    * CompareTags.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 CompareTags {
    private final static String xmlFileName = "C:/input.xml";
         int totalelements = 0;
    /** Creates a new instance of ParseXMLFile */
    public CompareTags() {
    // 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("totalelements in xyz tag " + totalelements);
              System.out.println("... end of statement");
    /** 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();
              //int totalelements = 0;
    for (int i = 0; i < children.getLength(); i++) {
    Node child = children.item(i);
                   //     System.out.println("child value.."+child);
    if (child.getNodeType() == Node.ELEMENT_NODE) {
    writeDocumentToOutput(child,indent + 2);
                             if(node.getNodeName() == "DATA"){
                             totalelements = totalelements+1;}
                        //System.out.println("totalelements in DATA tag " + totalelements);
    /** 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 CompareTags();
    }

    hi,
    check out the following links
    Check this blog to extract from XML:
    /people/kamaljeet.kharbanda/blog/2005/09/16/xi-bi-integration
    http://help.sap.com/saphelp_nw04/helpdata/en/fe/65d03b3f34d172e10000000a11402f/frameset.htm
    Check thi link for Extract from any DB:
    http://help.sap.com/saphelp_nw04s/helpdata/en/58/54f9c1562d104c9465dabd816f3f24/content.htm
    regards
    harikrishna N

  • Place contents of xml file to 2D array

    i have a xml file like
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE map SYSTEM "map.dtd">
    <map width="5" height="5" goal="6" name="Hallways of Dooom">
         <random-item type='lantern' amount='5' />
         <random-item type='health' amount='10' />
         <tile x="1" y="0" type="floor">
              <renderhint>floor:wood</renderhint>
         </tile>
         <tile x="0" y="1" type="wall" />
         <tile x="1" y="1" type="floor" startlocation="1" />
         <tile x="3" y="1" type="floor">
              <item type="treasure">Bar of Silver</item>
              <renderhint>floor:stone,blood</renderhint>
         </tile>
    </map>i was asked to creat a 5*5 2D array from it. each tile represents a position on the point. If the type of tile is wall, it is represented by number 2; if it is floor, it is represented by number 1.
    i have written my code as following:
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.ParserConfigurationException;
    import org.w3c.dom.*;
    import org.xml.sax.SAXException;
    import java.io.*;
    public class parsexml
        public void parseXML()
         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
         factory.setValidating(true);
         factory.setIgnoringElementContentWhitespace(true);
         try {
             DocumentBuilder parser = factory.newDocumentBuilder();
             Document doc = parser.parse(new File("hallways.xml"));
             System.out.println("XML file parsed.");
             processTree(doc);
         } catch (ParserConfigurationException e) {
             e.printStackTrace();
         } catch (SAXException e) {
             e.printStackTrace();
         } catch (IOException e) {
             e.printStackTrace();
        public void processTree(Document doc)
         int column = 0;
         int row = 0;
         int hori = 0;
         int vert = 0;
         String Type = "";
         Node element = doc.getDocumentElement();
         NamedNodeMap attrs = element.getAttributes();
         for (int i = 0; i < attrs.getLength(); i++) {
             Node attr = attrs.item(i);
             String attrName = attr.getNodeName();
             if (attrName == "width") {
              column = Integer.parseInt(attr.getNodeValue());
             if (attrName == "height") {
              row = Integer.parseInt(attr.getNodeValue());
         int[][] map = new int[row][column];
         NodeList children = element.getChildNodes();
         for (int i = 0; i < children.getLength(); i++) {
             Node child = children.item(i);
             String nodeName = child.getNodeName();
             if (nodeName == "tile") {
              NamedNodeMap attributes = child.getAttributes();
              for (int a = 0; a < attributes.getLength(); a++) {
                  Node attribute = attributes.item(a);
                  String attributeName = attribute.getNodeName();
                  if (attributeName == "x") {
                   hori = Integer.parseInt(attribute.getNodeValue());
                  if (attributeName == "y") {
                   vert = Integer.parseInt(attribute.getNodeValue());
                  if (attributeName == "type") {
                   Type = attribute.getNodeValue();
             if (Type == "floor") {
              map[hori][vert] = 1;
             } else if (Type == "wall") {
              map[hori][vert] = 2;
         print(map);
        public void print(int[][] map)
         for (int r = 0; r < map.length; r++) {
             for (int c = 0; c < map[r].length; c++) {
              System.out.print(map[r][c]);
             System.out.println();
        public static void main(String[] args)
         parsexml xml = new parsexml();
         xml.parseXML();
    }When i run the program, i found it doesn't fills the spcified position on the array. all I get is a 5*5 grid of 0s.
    Can anyone tells me why? thank you in advance.

    Unless someone is willing to put in the time to do your job for you, you'll have to debug it yourself. Put in some debugging statements. In their simplest form this is just a bunch of System.out.println("your message here") calls where you put in messages describing the current point of execution (like what method you just started or are about to finish) and the values of relevant data (such as method parameters, loop indices, whatever you feel is important).
    Then run the program and see what it tells you.

  • Convert xml file to a 2D list - Urgent!!!

    I have a xml file like:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE map SYSTEM "map.dtd">
    <map width="5" height="3" goal="6" name="Hallways of Dooom">
         <random-item type='lantern' amount='5' />
         <random-item type='health' amount='10' />
         <tile x="1" y="0" type="floor">
              <renderhint>floor:wood</renderhint>
         </tile>
         <tile x="0" y="1" type="floor" />
         <tile x="1" y="1" type="floor" startlocation="1" />
         <tile x="2" y="0" type="wall" />
         <tile x="3" y="0" type="wall" />
         <tile x="3" y="1" type="floor">
              <item type="treasure">Bar of Silver</item>
              <renderhint>floor:stone,blood</renderhint>
         </tile>
    </map>and i want to convert it to a 2D list, with the x-value of the list is the width of the map and the y-value of the list is the height of the map. The x and y value in the tile indicates the position of the point.
    i have already parse the xml file to java using:
    public class parsexml
             public static void main(String[] args)
              DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
              factory.setValidating(true);
              factory.setIgnoringElementContentWhitespace(true);
              try {
                   DocumentBuilder parser = factory.newDocumentBuilder();
                   Document doc = parser.parse(new File("hallways.xml"));
                   System.out.println("XML file parsed.");
              } catch (ParserConfigurationException e) {
                   e.printStackTrace();
              } catch (SAXException e) {
                   e.printStackTrace();
              } catch (IOException e) {
                   e.printStackTrace();
    }Can anyone give me any hint on what to do next. Thank you very much.

    mujingyue wrote:
    Thank you for your poem, it is the hightlight of my miserable day.
    but, any suggestions?Sure....
    You play tricks on my mind
    You're everywhere but you're so hard to find
    You're not warm or sentimental
    You're so extreme, you can be so temperamental
    But I'm not looking for a love that will last
    [ Urgent song text brought to you by LyricsYouLove ]
    I know what I need and I need it fast
    Yeah, there's one thing in common that we both share
    That's a need for for each other anytime, anywhere
    It gets so urgent
    So urgent
    You know it's urgent
    I wanna tell you it's the same for me
    So oh oh urgent
    Just you wait and see
    How urgent our love can be
    It's urgent
    You say it's urgent
    Make it fast, make it urgent
    Do it quick, do it urgent
    Gotta rush, make it urgent
    Want it quick
    Urgent, urgent, emergency
    Urgent, urgent, emergency
    Urgent, urgent, emergency
    Urgent, urgent, emergency
    So urgent, emergency
    Emer... emer... emer...
    It's urgent

  • Xerces - validator won't catch wrong input in xml file

    Hi there,
    I am using xerces 2.9.1 and Java 5
    here is my code
    package xmltesting;
    import java.io.IOException;
    import org.apache.xerces.parsers.DOMParser;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.NodeList;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXNotRecognizedException;
    import org.xml.sax.SAXNotSupportedException;
    public class DomParserExample {
         Document dom;
         public DomParserExample() {
         public void runExample() {
              //parse the xml file and get the dom object
              parseXmlFile();
         private void parseXmlFile(){
              //get the factory
              DOMParser parser = new DOMParser();
              try {
                   parser.setFeature("http://apache.org/xml/features/validation/schema",true);
              } catch (SAXNotRecognizedException e) {
                   e.printStackTrace();
              } catch (SAXNotSupportedException e) {
                   e.printStackTrace();
              try {
                   ErrorChecker errors = new ErrorChecker();
                   parser.setErrorHandler(errors);
                   //parse using builder to get DOM representation of the XML file
                   parser.parse("xmltesting/shiporder.xml");
                   dom = parser.getDocument();
              } catch(IOException ioe) {
                   ioe.printStackTrace();
              } catch (SAXException saxe) {
                   saxe.printStackTrace();
              System.out.println("Everything parsed without any problem");
         public static void main(String[] args){
              //create an instance
              DomParserExample dpe = new DomParserExample();
              //call run example
              dpe.runExample();
    }My xml is following
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <shiporder orderid="889923"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="shiporder.xsd">
    <orderperson>John Smith</orderperson>
    <shipto>
      <name>Ola Nordmann</name>
      <address>Langgt 23</address>
      <city>4000 Stavanger</city>
      <country>Norway</country>
    </shipto>
    <item>
      <title>Empire Burlesque</title>
      <note>Special Edition</note>
      <quantity>1</quantity>
      <price>10.90</price>
    </item>
    <item>
      <title>Hide your heart</title>
      <quantity>1</quantity>
      <price>9.90</price>
    </item>
    </shiporder>
    </xs:schema>and schema xsd is
    <?xml version="1.0" encoding="ISO-8859-1" ?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="shiporder">
    <xs:complexType>
      <xs:sequence>
       <xs:element name="orderperson" type="xs:string"/>
       <xs:element name="shipto">
        <xs:complexType>
         <xs:sequence>
          <xs:element name="name" type="xs:string"/>
          <xs:element name="address" type="xs:string"/>
          <xs:element name="city" type="xs:string"/>
          <xs:element name="country" type="xs:string"/>
         </xs:sequence>
        </xs:complexType>
       </xs:element>
       <xs:element name="item" maxOccurs="unbounded">
        <xs:complexType>
         <xs:sequence>
          <xs:element name="title" type="xs:string"/>
          <xs:element name="note" type="xs:string" minOccurs="0"/>
          <xs:element name="quantity" type="xs:positiveInteger"/>
          <xs:element name="price" type="xs:decimal"/>
         </xs:sequence>
        </xs:complexType>
       </xs:element>
      </xs:sequence>
      <xs:attribute name="orderid" type="xs:string" use="required"/>
    </xs:complexType>
    </xs:element>
    </xs:schema>Now I wanted to try and create problems in the xml file so the validator can catch those errors so i changed the quantity and price values to 'abc' string (they should be integer and decimal values respectively) everywhere in the xml file BUT the validation did not throw any errors and that is where i am confused.
    do i need to do something else in the Java code?
    thanks
    Edited by: Shazmiester on Aug 11, 2008 10:20 AM
    Edited by: Shazmiester on Aug 11, 2008 10:25 AM

    here is my ErrorChecker code
    package xmltesting;
    import org.xml.sax.helpers.DefaultHandler;
    import org.xml.sax.SAXParseException;
    public class ErrorChecker extends DefaultHandler
         public ErrorChecker() {
         public void error (SAXParseException e) {
              System.out.println("Parsing Error: " + e.getMessage());
         public void warning (SAXParseException e) {
              System.out.println("Parsing warning: " + e.getMessage());
         public void fatalError(SAXParseException e) {
              System.out.println("Fatal Parsing Error.: " + e.getMessage());
              System.out.println("Exiting...");
              System.exit(1);
    }Looks ok to me, the warnings don't show up at all.

  • Reading external xml files from a jar

    Hi,
    I am trying to read an xml file from a jar (which is not present inside the jar ) .
    I am passing the file name as a string (like C:/folder/filename) to the SAXBuilder but it throwing
    unknown protocol: c error.
    i tried using an url , tried using a relative path but to no use.
    Need help in this regard urgently.
    TIA,
    Regards,
    Harsha

    Hi,
    Actually, my application needs to read two xml files , parse it, perform some operation and write
    the result to an output file.
    The names of the two xml files i mentioned, are specified in a properties file as absolute paths. (I even tried converting them to URIs)
    The xml files are in the same directory as the jar ( i dont know if it should matter as i am giving the absolute path).
    The main class reads the names of the files and passes the names as strings to the SAXBuilder.
    This is where i am getting an exception.
    Going by what you said, is it not possible for a java class to read a fie outside of the jar ? Is there no way to do this ? And right now i am not sure of how to go about this or if there's any work around . Any help would be appreciated.
    Kindly reply at the earliest
    TIA,
    Harsha

  • Reading/writing XML files

    hi
    i want to makeXML based config files for my system,i didn`t example to write/read XML files(parsing).
    please provide some example ,Also,is there some alternative for readind data?
    Thanks

    See for example XML rlated taglibs in Coldtags suite:
    http://www.servletsuite.com/jsp.htm

  • Saving business objects into xml file

    I have the following XML file parsed into a DOM tree, with 2 different types of nodes "TestCase" and
    "RealCase". Then I mapped each type to a different type of business object, TestCaseObj and RealCaseObj.
    Now, there may be addition of new objects, or modifications to the data stored in the business objects
    by my application. Eventually when I save the business objects back into the XML file, how should I go
    about doing that?
    <ROOT>
    <TestCase TestID="T1">
         <Element1>Data1</Element1>
         <Element2>Data2</Element2>
    </TestCase>
    <TestCase TestID="T2">
         <Element1>Data1</Element1>
         <Element2>Data2</Element2>
    </TestCase>
    <RealCase ID="R1">
         <Element1>Data1</Element1>
         <Element2>Data2</Element2>
         <Element3>Data3</Element3>
    </RealCase>
    <RealCase ID="R2">
         <Element1>Data1</Element1>
         <Element2>Data2</Element2>
         <Element3>Data3</Element3>
    </RealCase>
    </ROOT>

    The DocumentBuilder class does not allow you to parse a portion of the xmlfile. Therefore, it will not be possible to read "TestCase" into the DOM without bringing in "RealCase" nodes as well. As such, these codes will parse the entire xml file into DOM:
    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    Document document = builder.parse( xmlFile );
    However, your problem can be solved by reading only "TestCase" nodes in DOM, as follows:
    NodeList elementNodeList =
    elementNode.getElementsByTagName("TestCase");
    Your codes will then change the data in the elementNodeList, without affecting "RealCase" although it is loaded into DOM. You can be sure that elementNodeList contains only "TestCase" nodes.
    Once you have made your changes, save the DOM back to the XML file, using the serializer method as discussed earlier.
    Good luck.

Maybe you are looking for

  • Is it possible to have two encrypted time machines on one partitioned hard drive?

    I am trying to use encrypted time machines for two macbooks (15" and 11") with only one USB hard drive. The problem is that after creating one encrypted time machine for my 15" in a separate partition, the hard drive does not work when plugging it in

  • IPad 4 with iOS 8 "read list" doesn't work

    After updating to iOS 8, read list  feature in Safari doesn't work animore!!!((( I can not read articles without the intertnet! And also, Apple, come on, make iWork for free for rest of you costomers! It's ridicules to pay 30$ just only because that

  • AP Controller IP DHCP Problem

    Dear all, its not my first config or location but with the 2600 I have now a problem. Any ideas? *Mar  1 00:17:04.255: %CAPWAP-3-DHCP_RENEW: Could not discover WLC using DHCP IP. Renewing DHCP IP. *Mar  1 00:17:07.327: %DHCP-6-ADDRESS_ASSIGN: Interfa

  • OCP 9i Certification Requirements

    Hi All, i had finished all the following exams 1z0-007,1z0-031,1z0-032 and 1z0-033 along with all the below courses ILT - Training Oracle 9i Introduction to SQL Course Oracle 9i fundamentals I Course Oracle 9i fundamentals II Course Oracle 9i Perform

  • Flash breaks randomly, won't compile, ignores document class?

    I have run into a strange and annoying problem since updating to Flash Professional CS5.5 on my work computer. Sometimes, seemingly randomly, Flash stops compiling things correctly. I Test Movie by hitting Cmd+Return and it just displays what's on th