Parse XML file and extract data

I'd like to parse an XML file and get some data extracted as columns.
Input file country.xml:
<?xml version="1.0" encoding="UTF-8"?>
<MAS Action="Insert">
<Country ObjectId="100000000000000009" VersionId="8"><Id>1</Id><NlTexts><Name Language="de">Land1</Name><Name Language="en">Country1</Name></NlTexts></Country>
<Country ObjectId="100000000000000033" VersionId="2"><Id>2</Id><NlTexts><Name Language="de">Land2</Name><Name Language="en">Country1</Name></NlTexts></Country>
</MAS>
I'd like to parse the xmlfile in order to get the following output
Required result:
col1        col2           col3
1            Land1        Country1
2            Land2        Country2
or alternatively
col1  col2      
1            Land1      
1            Country1
2            Land2      
2            Country2
I tried extract-function
select extract((XMLTYPE(BFILENAME('XML_DAT_DIR', 'country.xml'),
           NLS_CHARSET_ID('AL32UTF8'))) , '/*/*/Id') as "xdata"
from dual;
xdata
<Id>1</Id><Id>2</Id>
and XMLTABLE (but how can I add the countries now)
SELECT *
    FROM XMLTABLE('/*/*/Id'
           PASSING XMLTYPE(BFILENAME('XML_DAT_DIR', 'country.xml'),
           NLS_CHARSET_ID('AL32UTF8'))
COLUMN_VALUE
<Id>1</Id>
<Id>2</Id>
DB version 11.2.0.3 on Windows 64bit
Thanks,
Tim

Here are a few examples.
For your required output :
SELECT *
FROM XMLTable(
       '/MAS/Country'
       passing XMLType(bfilename('TEST_DIR', 'country.xml'), nls_charset_id('AL32UTF8'))
       columns col1 number       path 'Id'
             , col2 varchar2(30) path 'NlTexts/Name[1]'
             , col3 varchar2(30) path 'NlTexts/Name[2]'
or, if the Language attribute is significant :
SELECT *
FROM XMLTable(
       '/MAS/Country'
       passing XMLType(bfilename('TEST_DIR', 'country.xml'), nls_charset_id('AL32UTF8'))
       columns col1 number       path 'Id'
             , col2 varchar2(30) path 'NlTexts/Name[@Language="de"]'
             , col3 varchar2(30) path 'NlTexts/Name[@Language="en"]'
For your alternate output :
SELECT x1.col1
     , x2.col2
     --, x2.col3
FROM XMLTable(
       '/MAS/Country'
       passing XMLType(bfilename('TEST_DIR', 'country.xml'), nls_charset_id('AL32UTF8'))
       columns col1  number  path 'Id'
             , names xmltype path 'NlTexts/Name'
     ) x1
   , XMLTable(
       '/Name'
       passing x1.names
       columns col2 varchar2(30) path '.'
             --, col3 for ordinality
     ) x2
(uncomment col3 to see what it does)
or, in a shorter way :
SELECT *
FROM XMLTable(
       'for $i in /MAS/Country
          , $j in $i/NlTexts/Name
        return element r { $i/Id, $j }'
       passing XMLType(bfilename('TEST_DIR', 'country.xml'), nls_charset_id('AL32UTF8'))
       columns col1 number       path 'Id'
             , col2 varchar2(30) path 'Name'

Similar Messages

  • Parse xml file and extract tags (not well formed)

    im writing an xml editor and i would like to extract tags from a string of xml. And the string doesnt have to be well formed xml.
    An example "</a><b asd="kjkj"></b>"
    Output
    end tag (a)
    start tag (b)
    end tag (b)
    Sax nor stax does the job since they want well formed document. and i dont want to write a parser myself.
    any suggestions

    im writing an xml editor and i would like to extract
    tags from a string of xml. And the string doesnt have
    to be well formed xml.Then you aren't writing an XML editor. And as you observe, existing parsers don't work for you because they are don't have the requirement to process garbage. Where did you get that requirement from, anyway?

  • Please recommend if we have options to read xml file and insert data into table without a temporary table.

    Please recommend if we have options to read xml file and insert data into table without a temporary table. 

    DECLARE @data XML;
    SET @data =N'<Root>
    <List RecordID="946236" />
    <List RecordID="946237" />
    <List RecordID="946238" />
    <List RecordID="946239" />
    <List RecordID="946240" />
    </Root>'
    INSERT INTO t (id) SELECT T.customer.value('@RecordID', 'INT') AS id
    FROM @data.nodes('Root/List')
     AS T(customer);
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • Create xml file and write data in to it:

    Hi All,
    I have a small requirement here.....
    I have a java program which reads a xml file.
    Now i have stored the contents of that file in to a java object.
    I want a sample code now which would take theabove mentioned java object as an input ,create a xml file and write these entries in to the file.
    Can anyone help me in this?
    Your help would be appreciated.
    Thanks in advance.
    vrkr

    Hmmm. There is nothing special about an XML file to any other file. The data is simply formatted in a certain way. So to write an XML file, it is no different to writing any other form of file in Java (assuming you know the structure of the xml format to write - which you should)
    If you don't know how to write files using Java I would suggest using the Java Tutorial found on java.sun.com and do some reading up about I/O since this is fairly fundamental.
    http://java.sun.com/docs/books/tutorial/
    http://java.sun.com/docs/books/tutorial/essential/io/index.html

  • Reading a xml file and Extract content of xml tags

    Hi,
    I need a InDesign script to Extract content of xml tags by reading a local xml file. And stamping the content of xml on InDesign Text frame.
    My sample xml is as follows .
    <events type="array">
    <event> 
    <aktiv_jn>J</aktiv_jn> 
    <enetpulse_id>1712408</enetpulse_id>
    <event_id>65974</event_id>
    <hjemmehold>AZ Alkmaar</hjemmehold>
    <id>93</id>
    <kickoff>2014-08-17T12:30:00+01:00</kickoff>
    <land_id>140</land_id>
    <land_navn>Holland</land_navn>
    <liga_id>13684</liga_id>
    <liga_navn>Eredivisie</liga_navn>
    <livebetting_jn>J</livebetting_jn>
    <marked_id>2897740</marked_id>
    <marked_nummer>138</marked_nummer>
    <marked_tekst>AZ Alkmaar - Ajax</marked_tekst>
    <moderkamp_jn>J</moderkamp_jn>
    <ob_bet_type>MR</ob_bet_type>
    <odds_1>2.95</odds_1>
    <odds_2>2.25</odds_2>
    <odds_x>3.35</odds_x>
    <program_slut>2014-08-18T23:59:00+01:00</program_slut>
    <program_start>2014-08-15T00:00:00+01:00</program_start>
    <resultat>2</resultat>
    <spilstop_dato_tid>2014-08-17T12:30:00+01:00</spilstop_dato_tid>
    <sport_id>21</sport_id>
    <sport_navn>Fodbold</sport_navn>
    <taerskel nil="true"/>
    <udehold>Ajax</udehold>
    <udfald_1_id>9661951</udfald_1_id>
    <udfald_2_id>9661953</udfald_2_id>
    <udfald_x_id>9661952</udfald_x_id>
    </event>
    </events>
    And on my Indesign Page upon execution of script: I need text like,
    land_navn:     Holland
    odds_1:     2.95
    odds_2:     2.25
    odds_x:     3.35

    Hi,
    Try:

  • Comparing an excel file to and xml file and appending data to the xml file

    I have an xml file (mapsource) and an excel file. One of the columns in the excel file matches up with a node in the xml file. I want to be able to loop through both files and add a new node to the xml file where the one of the columns in the excel file matches a node in the xml file.
    I can create a query object out of the excel dosument using the cfspreadsheet tag.
    I'm able to use xmlparse to create a xml document object from the xml file.
    What I would like to do is add col_3 from the excel spreadsheet as a new node when col_2 is equal to gpx.wpt.name.xmltext of the xml object.
    Any help or direction would be very helpful!

    Hi,
    Thank you for your reply. But I have to attach an excel file from a particular path (C:\TEMP\TEST.XLS) and I have to send that excel file to the user inbox.That excel file has multiple sheets with data. Can you please provide me any code is available.
    Thanks and Regards
    venkat.

  • Parse a WebPage and Extract Data

    Hi, i've figured out how to get an html source using a java class posted earlier on this forum. I wanted to find out what is the best and easiest way to extract information from it. I have been searching the web and read a lot about using XML. Is that the best way to do it, or is there something else i can use ? Thanks !

    I would suggest building your own statements.
    I am not sure which web site you are trying to get data from. However the previous response was correct. HTML has to be well formed which often it is not. Even the most professional web sites have bad HTML code.
    I am not sure if you are looking to extract data from one web site or various (please let me know).
    here is an example of how you 'might' wish to do it:
    HTML CODE:
    <td nowrap><font face="Arial" size="3"><b>Description</b></font></td>
    <td width="100%"></td>
    <td nowrap width="100%" align="right">WonderfulDescription</font>
    </td>
    CODE:
    String description  //Field to store the description
    int startIndex      //Index of where description starts
    int endIndex        //Index of where description ends
    while (readLine...)     //That while loop from the previous code I gave
      if (readLine.indexOf("Description" != -1)
        HTMLpage.readLine(); // Read line 1 - hence: <td width="100%"></td>
        readLine = HTMLpage.readLine();
        startIndex = readLine.indexOf("align=\"right\">") + 14;
        endIndex = readLine.indexOf("</font>"); 
        description = readLine.subString(startIndex, endIndex);
    }This is ideal if there is specific information in the page that you wish to obtain. But coding it takes time and you have to study the web page layout carefully. I suggest putting a System.out.println(readLine) statement in the while loop. The copying and pasting the output into FrontPage and looking at it. Dont copy and paste the source from ViewSource in Internet Explorer as it will not show you dynamic data.
    Let me know how you get on. As always, get back to me if you have any questions.
    Kind regards
    Angus

  • Parse text file and retrieve data

    Hi,
    I have a log file with comma separated entries in each line. Each line has about 50 or more integer values logged for statistical analysis. What i need to do is to be able to parse this text file Line by line and retrieve data say nth entry in each row of file. Basically, like i need a certain column from a table. Column selection may vary. I can have user need 10th entry or 25th entry or more than one entries.
    Please help me with suggestions for how to do this efficiently . Keep in mind log file can be huge at certian times.
    Thanks
    -Anupma

    here's something to get you started
    public void parseFile(File file) throws IOException{
        String lin = null;  // string to hold each line in the text file
        BufferedReader in = new BufferedReader(new FileReader(file));
        while ((line = in.readLine()) != null){
            processLine(line);
    public void processLine(String line){
        String tokens = line.split(",");     // tokenize the line - deliminator is a comma
        for (int i = 0; i < tokens.length; i++){
            try{
                int num = Integer.parseInt(tokens);
    System.out.println(" The integer is = " + num);
    catch(NumberFormattedException ee){}

  • 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

  • Parse XML files

    Hi
    Anyone know about support for parsing XML files in LabVIEW?
    (I mean specific XML support, I'm familiar with LabVIEWs file functions)
    regards
    Jan
    Sent via Deja.com http://www.deja.com/
    Before you buy.

    I assume you are referring to:
    http://www.savarese.org/oro/software/OROMatcher1.1.html
    Have you considered asking Savarese?
    Peace,
    Cameron Purdy
    Tangosol, Inc.
    http://www.tangosol.com
    +1.617.623.5782
    WebLogic Consulting Available
    "Laurent Mentek" <[email protected]> wrote in message
    news:[email protected]..
    Hi all,
    I'm started to develop with BEA WebLogic and I use ORACLE 8.1.6
    database.
    We need to map some XML tags as metadata in the database.
    Here is a concrete example with part of our XML files:
    XML files :
    <target>EDU</target>
    <question>
    <para>
    Please could you provide some references on nutritional status in
    the frail elderly?
    </para>
    </question>
    I use OROMatcher to parse xml files and it work fine.
    I can extract every element in line with success , but don't extract the
    value in <para> tag, for example.
    I don't no how to use the MULTILINE_MASK option and the ^ or $ to get
    this line.
    Anyone could give me an example of metadatas extaction using or no the
    MULTILINE_MASK option?
    Thanks a lot for your help.
    Laurent.

  • How to parse xml file in midlet

    Hi Guys,
    i wish to parse xml file and display it in my midlet. i found api's supporting xml parsing in j2se ie., in java.net or j2se 5.0. Can u please help me what package to use in midlet?
    how to parse xml info and display in midlet? Plz reply soon......Thanks in advance....

    i have exactly the same problem with KXml2, but using a j2me-polish netbeans project.
    i've tried to work around with similar ways like you, but none of them worked. now i've spent 3 days for solving this problem, i'm a bit disappointed :( what is wrong with setting the downloaded kxml2 jar path in libraries&resources?
    screenshot

  • Hi, extract data from xml file and insert into another exiting xml file

    i am searching code to extract data from xml file and insert into another exiting xml file by a java program. I understood it is easy to extract data from a xml file, and how ever without creating another xml file. We want to insert the extracted data into another exiting xml file. Suggestions?
    1st xml file which has two lines(text1.xml)
    <?xml version="1.0" encoding="iso-8859-1"?>
    <xs:PrintDataRequest xmlns:xs="http://com.unisys.com/Anid"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://com.unisys.com/Anid file:ANIDWS.xsd">
    <xs:Person>
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://com.unisys.com/Anid file:ANIDWS.xsd">
    These two lines has to be inserted in the existing another xml(text 2.xml) file(at line 3 and 4)
    Regards,
    bubbly

    Jadz_Core wrote:
    RandomAccessFile? If you know where you want to insert it.Are you sure about this? If using this, the receiving file would have to have bytes inserted that exactly match the number of bytes replaced. I'm thinking that you'll likely have to stream through the second XML with a SAX parser and copy information (or insert new information) as you stream with an XML writer of some sort.

  • Stuck parsing an InDesign document, extracting data to an XML file

    Hi,
    I have an indesign document of a newspaper page (1 spread + 1 page) with some articles (title, body, img, img caption) and ads (img). I need to parse this and create an XML file from which data can be stored into a mysql db. The db handling is already programmed.
    The xml file will have this structure (page = root):
    <page>
         <article>
              <title>Title</title>
              <content>Lorem ipsum</content>
              <img title=""></img>
         </article>
         <ad>
              <img title=""></img>
         </ad>
    </page>
    The .indd file is created using the Smart Layout plugin from WoodWing software. When trying to print the "TextFrames>Texts>contents" the textframes that use the smart layout plugin do not show, they seem to be not included in the data model of the app. That's why I went another route, and parsed "Stories>Texts>contents". I can get all the text objects of the page, including the articles that are created using the smart layout plugin. Among these objects are article title's and article bodies. The problem is I don't know which title belongs to which body, so I can't create a new article node in the XML. I have exported the orignal file as IDML and browsed the spread and the stories, but I see no way to link article titles (textframe), article bodies (textframe) and images (contained by rectangles) together.
    Is there a way to solve this?
    Setup:
    InDesign CS4 .indd documents
    Win2k8 server
    JavaScript (via ExtendScript toolkit)
    InDesignServer CS5.5 (64bit) (want to use this)
    SmartLayout plugin (installs @ InDesignServer CS5.5 32bit. This 32bit InDServer does not start, it has missing dll's).

    I am building something similar, and I have much of it working. Respond here if you're still interested, and hopefully I'll see it!

  • How to extract data from xml file and store that data inti data base table

    Hii All
    I have one table that table contains one column that column contain an XML file
    I want to extract data from that XML file and want to store that extracted data into an other table.
    That xml file has different different values
    I want to store that values into table in diff diff columns

    Hi,
    I am also facing the same problem.I have a .xml file and i need to import the data into the custom table in oracle database.
    Can you please let me know if you know the solution how to do it in oracle apps.
    Thanks,

  • Extract data from xml file and insert into another exiting xml fil

    hello,
    i am searching extract data from xml file and insert into another exiting xml file by a java program. I understood it is easy to extract data from a xml file, and how ever without creating another xml file. We want to insert the extracted data into another exiting xml file. Suggestions?
    Regards,
    Zhuozhi

    If the files are small, you can load the target file in a DOM document, insert the data from the source file and persist the DOM.
    If the files are large, you probably want to use a StAX or SAX.

Maybe you are looking for

  • JAVA Patches not deployed properly-System restore back

    Hi Experts! recently we had deployed JAVA patches on EP development box but we are facing lot of problems with functionality and etc.Before going to deployment,we took backup for file system as well database.So we are planning to restore it back.My d

  • Excel Add-in Warning message

    Everytime I connect to Essbase via the Add-in I get the following warning: "This version of Essbase (93000) is older than the version of the Essbase API (93100) you are using." I know what the error means and also know that the versions are compatibl

  • Keep getting message from sites that Adobe Flash Player needs to be installed

    I have a MacBook, OSX 10.7.5.  When I try to download a document, I am told that I need Adobe Flash Player and that I should download it. When I look on the Adobe website, to check something, I see that the newest version of Flash Player is installed

  • Webi error as a Bex query data source

    Hi All, I am getting the below error When i try to access Bex query from Webi with OLAP connection as SSO, if it is predefined it works good, for predefined i used Service account for now. com.businessobjects.sdk.core.server.CommunicationException$Un

  • How do we compare two images in labview?

    I have created a back end code which is comparing two images using LABVIEW.i have used a comparator and put a tolerance factor which will help me filter out almost same images.the problem i am facing is that on subtraction of the given two images i a