Read an XML file with namespace items

I'm a beginner with XML and for the first time i have to read a file with columns.
I have try this code, but the result is always the same: no rows selected.
variable xml_response varchar2(4000)
BEGIN
:xml_response :=
<?xml version="1.0" encoding="UTF-8"?>
<ROOT xmlns="http://www.post.ch/schemas/dfu/2006/20/Report11">
  <Sender SenderID="1618" SenderName="Laurastar SA" ReportCreated="20141120053155">
  <Provider ProviderID="539ADAEE-FF18-49F8-84B8-B90232CBCC61" ProviderName="Pakete">
  <Data>
  <Item SendingID="a68f0007-c4df-4ecb-8dfe-d6da6c2e0cda" ItemID="5430243" IdentCode="993314781300000254" />
  <Item SendingID="beba5a0e-6363-42f1-aeb5-51c5171ed032" ItemID="5430241" IdentCode="993314781300000255" />
  <Item SendingID="beba5a0e-6363-42f1-aeb5-51c5171ed032" ItemID="5430241" IdentCode="993314781300000255" />
  </Data>
  </Provider>
  </Sender>
</ROOT>';
END;
SELECT x.*
   FROM XMLTable(
   '/ROOT'
   passing xmltype(:xml_response)
   columns
  ReportCreated varchar2(30)  path 'Sender/@ReportCreated'
   , SendingID  varchar2(50)  path 'Sender/Provider/Data/Item/@SendingID'
   , ItemID  varchar2(30)  path 'Sender/Provider/Data/Item/@ItemID'
   , IdentCode  varchar2(30)  path 'Sender/Provider/Data/Item/@IdentCode'
   ) x
I could not found what is wrong.

I could not found what is wrong.
Two things are wrong :
1) Lack of namespace declaration
2) You're trying to project repeating nodes into a single row
This should work :
SELECT x1.ReportCreated
     , x2.*
FROM XMLTable(
       XMLNamespaces(default 'http://www.post.ch/schemas/dfu/2006/20/Report11')
     , '/ROOT/Sender'
       passing xmltype(:xml_response)
       columns
         ReportCreated varchar2(30) path '@ReportCreated'
       , items         xmltype      path 'Provider/Data/Item'
     ) x1
   , XMLTable(
       XMLNamespaces(default 'http://www.post.ch/schemas/dfu/2006/20/Report11')
     , 'Item'
       passing x1.items
       columns
         SendingID     varchar2(50)  path '@SendingID'
       , ItemID        varchar2(30)  path '@ItemID'
       , IdentCode     varchar2(30)  path '@IdentCode'
     ) x2

Similar Messages

  • How must getElementsByTagName work on an xml file with namespaces?

    Hello together,
    is there any normative document, which specifies
    which nodes must be returned by
    the org.w3c.dom.Document method
    getElementsByTagName when which was
    created by a namespace aware dom parser
    from an xml file containing namespaces?
    In other words:
    when you have an xml file:
    <someprefix:somenode xmlns:someprefix="http://someuri">
    <someprefix:innertag>
    <someprefix:mostinnertag>
    </someprefix:mostinnertag>
    <someprefix:mostinnertag>
    </someprefix:mostinnertag>
    </someprefix:innertag>
    </someprefix>
    and you call
    document.getElementsByTagName( ... );
    1) How many nodes must be returned when giving
    "mostinnertag" as parameter?
    2) How many nodes when giving "someprefix:mostinnertag" as parameter?
    Is it allowed to use the "non namespaceaware"
    method and not "getElementsByTagNameNS"?
    I know:
    a) xerces returns 2 nodes when using
    alternative 2 and none with alternative 1
    b) oracle xml parser returns 2 nodes when using
    alternative 1 and none when using alternative 2
    Which implementation is right?
    Yours
    Stefan

    I've got some problems with this methos and xerces too.
    Perhaps the two implementations (xerces and oracle) are different. I mean xerces implementation gives you nodes of this name but without namespace and oracles's implementation gives you modes with namespace whose unprefix-name is "mostinnertag".

  • Read an XML file with java: Document to Node conversion

    Hello,
    I want to read an XML file and convert data into a Node instance because I need this for an XForm application.
    My code is:
    private Node workstationType;
    public Node initModel() {
    try {
    //This one will hold the results
    Document document;
    //loading from XML File
    String fileName="C:\\documents\\iniForm.xml";
    FileInputStream inXML = new FileInputStream(fileName);
    BufferedReader in = new BufferedReader(new InputStreamReader(inXML));
    document = XMLLoader.loadFromStream(in);
    } catch (Exception e) {
    System.err.println("ERROR:" + e.getMessage());
    e.printStackTrace(System.err);
    //Create the node for the root, 'typeOfWorkstation'
    workstationType = document.getDocumentElement(); //A
    //Return the root node
    return (workstationType);
    The problem: I can convert Node instance to Document instance (line A)
    The error message is: "document cannot be resolved".
    How can I do that??
    Thank you
    Sylvain

    Here is my XMLLoader class:
    public class XMLLoader {
         public static Document loadFromStream(Reader reader) throws Exception {
              //Build a DOM document with the reader
              //prepare DOM document
              DOMImplementation impl;
              DocumentBuilder builder;
              try {
                   // Find the implementation
                   DocumentBuilderFactory factory =
                        DocumentBuilderFactory.newInstance();
                   factory.setNamespaceAware(false);
                   factory.setValidating(false);
                   builder = factory.newDocumentBuilder();
                   impl = builder.getDOMImplementation();
                   //Read and parse the XML input stream into a DOM document
                   Document document = builder.parse(new InputSource(reader));
                   return document;
              } catch (IOException ex) {
                   throw new RuntimeException(
                        "[XMLLoader.loadFromFile]: Failed loading the InputStream. Root cause: \n"
                             + ex);
              } catch (Exception ex) {
                   throw new RuntimeException(
                        "[XMLLoader.loadFromFile]: Failed to initialize DOM factory. Root cause: \n"
                             + ex);

  • How To read an XML file with JDom

    I have read through some tutorials after installing JDom on how to read an existing XML file and I was confused by all of them. I simply want to open an XML file and read one of the node's content. Such as <username>john doe</username> this way I can compare values with what the user has entered as their username. I am not sure were to start and I was hoping someone could help me out.
    I know that this seems like an insecure way to store login information but after I master opening and writing XML files with JDom I am going to use AES to encrypt the XML files.

    Here is a test program for JDom and XPath use considering your XML file is named "test.xml" :import org.jdom.input.*;
    import org.jdom.xpath.*;
    public class JDomXPath {
    public static void main(String[] args) {
      SAXBuilder saxBuilder = new SAXBuilder("org.apache.xerces.parsers.SAXParser");
      try {
       org.jdom.Document jdomDocument = saxBuilder.build("test.xml");
       org.jdom.Element usernameNode = (org.jdom.Element)XPath.selectSingleNode(jdomDocument, "//username");
       System.out.print(usernameNode.getText());
      } catch (Exception e) {
       e.printStackTrace();
    }(tested with Eclipse)

  • How to read a xml file with StringReader class

    Hi,
    I need to read a XML document with StringReade class. My aplication receives an absolute path but this doesn't work:
    StringReader oStringReader =
    new StringReader(c:\java\libros.xml);
    However it works with:
    StringReader oStringReader =
    new StringReader("<?xml version="1.0" e......");
    ie, with the whole document as a String, but I need to do it as the frist way.
    Thanks

    Hi,
    I need to read a XML document with StringReade class.
    My aplication receives an absolute path but this
    doesn't work:
    StringReader oStringReader =
    new StringReader(c:\java\libros.xml);
    However it works with:
    StringReader oStringReader =
    new StringReader("<?xml version="1.0" e......");
    ie, with the whole document as a String, but I need
    to do it as the frist way.
    Thankstake a look at this link:
    http://java.sun.com/webservices/jaxp/dist/1.1/docs/tutorial/sax/2a_echo.html

  • Read an XML file with Powershell ?

    Hi,
    Can someone please help. Is there a way in which powershell can check my 'example' xml file for an instance of 'BizTalk1' for Server1? Can PowerShell check <Group name="BiztalkGroup1" for <Name>BizTalk1 for Server1
    Hope my question makes sense. Thanks in advance
    <Config>
    <Defaults>
    <dgroup>BiztalkGroup1</dgroup>
    <dgroup>Services</dgroup>
    </Defaults>
    <Server name="Server1">
    <Services>
    <Group name="Services" order="1">
    <Items>
    <Name>Service 1</Name>
    <Name>Service 2</Name>
    </Items>
    </Group>
    </Services>
    <HostInstances>
    <Group name="BiztalkGroup1"<order="2">
    <Items>
    <Name>Biztalk1</Name>
    <Name>Biztalk2</Name>
    <Name>Biztalk3</Name>
    <Name>Biztalk4</Name>
    </Items>
    </Group>
    </HostInstances>
    </Server>
    <Server name="Server2">
    <Services>
    <Group name="Services" order="1">
    <Items>
    <Name>Service 1</Name>
    <Name>Service 2</Name>
    </Items>
    </Group>
    </Services>
    <HostInstances>
    <Group name="BiztalkGroup1"<order="2">
    <Items>
    <Name>Biztalk1</Name>
    <Name>Biztalk2</Name>
    <Name>Biztalk3</Name>
    <Name>Biztalk4</Name>
    </Items>
    </Group>
    </HostInstances>
    </Server>

    Hi jrv, I would like to test to see if a server has that value.
    My end goal is to have a checkbox on a form I have created to be ticked if the value exists for Server 1 and antoher Checkbox doing the same for Server2. There are 30 different values in the XML I need to check for.
    e.g: Does BizTalkGroup1 contain 'BizTalk1' for Server1, if true checkbox is ticked if false checkbox is NOT ticked.
    Thanks for your help.

  • Parsing this XML file with namespace

    I need to parse the following XML structure:
    <?xml version="1.0" encoding="utf-8"?>
    <ArrayOfTitles xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://example.com/">
      <Titles>
        <articleID>123</articleID>
        <articleTitle>Title 1</articleTitle>
      </Titles>
      <Titles>
        <articleID>456</articleID>
        <articleTitle>Title 2</articleTitle>
      </Titles>
      <Titles>
        <articleID>789</articleID>
        <articleTitle>Title 3</articleTitle>
      </Titles>
    </ArrayOfTitles>
    I am using this code:
    var ns:Namespace = new Namespace("http://example.com/");
    var strings:XMLList = xml.ns::Titles;
    for each(var str:XML in strings)
    trace(str);
    But the output still has the namespace in each node.

    Well, I have to say openning a new file writer every time you write a block of characters is pretty horrible, why not just use one buffered writer for the whole operation. I can't see the memory leak, but I think this would run agonisingly slowly.

  • File Adapter : read XML file with data validation and file rejection ?

    Hello,
    In order to read a XML file with the file adapter, I have defined a XSD that I have imported to my project.
    Now the File Adapter reads the file correctly but it does not give an error when:
    - the data types are not valid. Ex: dateTime is expected in a node and a string is provided
    - the XML file has invalid attributes.
    How can I manage error handling for XML files ?
    Should I write my own Java XPath function to validate the file after is processed ? (here is an example for doing this : http://www.experts-exchange.com/Web/Web_Languages/XML/Q_21058568.html)
    Thanks.

    one option is to specify validateXML on the partnerlink (that describes the file adapter endpoint) such as shown here
    <partnerLinkBinding name="StarLoanService">
    <property name="wsdlLocation"> http://<hostname>:9700/orabpel/default/StarLoan/StarLoan?wsdl</property>
    <property name="validateXML">true</property>
    </partnerLinkBinding>
    hth clemens

  • How to parse XML file with namesapce?

    Hi,
       I am trying to parse an xml file having namespace. But no data is returned.
    Sample Code:
    public class XMLFileLoader
    var xml:XML = new XML();
    var myXML:XML = new XML();
    var XML_URL:String = "file:///C:/Documents and Settings/Administrator/Desktop/MyData.xml";
    var myLoader:URLLoader = null;
    public function XMLFileLoader()
    var myXMLURL:URLRequest = new URLRequest(XML_URL);
    myLoader= new URLLoader(myXMLURL);
    myLoader.addEventListener(Event.COMPLETE,download);
    public function download(event:Event):void
    myXML = XML(myLoader.data);
    var ns:Namespace=myXML.namespace("xsi");
    for(var prop:String in myXML)
         trace(prop);
    //Alert.show(myXML..Parameters);
    //trace("Data loadedww."+myXML.toString());
    //Alert.show(myXML.DocumentInfo.attributes()+"test","Message");
    The XML Contains the following format.
    <Network xmlns="http://www.test.com/2005/test/omc/conf"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://www.test.com/2005/test/omc/conf/TestConfigurationEdition3proposal4.xsd">
        <TestDomain>
          <WAC>
            <!--Release Parameter  -->
            <Parameters ParameterName="ne_release" OutageType="None"
                        accessRight="CreateOnly" isMandatory="true"
                        Planned="false"
                        Reference="true" Working="true">
              <DataType>
                <StringType/>
              </DataType>
              <GUIInfo graphicalName="Release"
                       tabName="All"
                       description="Describes the release version of the managed object"/>
            </Parameters>
    </TestDomain>
    </Network>
    Any sample code how to parse this kind of xml file with namespaces...
    Regards,
    Purushotham

    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

  • Issue with reading a xml file from xsl

    Hi,
    When I am trying to read a xml file from xsl, I am getting unwanted output.
    Following is the XSL:
    <?xml version="1.0" encoding="UTF-8" ?>
    <?oracle-xsl-mapper
      <!-- SPECIFICATION OF MAP SOURCES AND TARGETS, DO NOT MODIFY. -->
      <mapSources>
        <source type="XSD">
          <schema location="../xsd/B2BMarketProperties.xsd"/>
          <rootElement name="ReceipentIDType" namespace="http://www.example.org"/>
        </source>
      </mapSources>
      <mapTargets>
        <target type="XSD">
          <schema location="../xsd/B2BMarketProperties.xsd"/>
          <rootElement name="ReceipentIDType" namespace="http://www.example.org"/>
        </target>
      </mapTargets>
      <!-- GENERATED BY ORACLE XSL MAPPER 11.1.1.4.0(build 110106.1932.5682) AT [TUE DEC 03 16:06:03 EST 2013]. -->
    ?>
    <xsl:stylesheet version="1.0"
                    xmlns:bpws="http://schemas.xmlsoap.org/ws/2003/03/business-process/"
                    xmlns:xp20="http://www.oracle.com/XSL/Transform/java/oracle.tip.pc.services.functions.Xpath20"
                    xmlns:mhdr="http://www.oracle.com/XSL/Transform/java/oracle.tip.mediator.service.common.functions.MediatorExtnFunction"
                    xmlns:bpel="http://docs.oasis-open.org/wsbpel/2.0/process/executable"
                    xmlns:oraext="http://www.oracle.com/XSL/Transform/java/oracle.tip.pc.services.functions.ExtFunc"
                    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                    xmlns:ns0="http://www.example.org"
                    xmlns:dvm="http://www.oracle.com/XSL/Transform/java/oracle.tip.dvm.LookupValue"
                    xmlns:hwf="http://xmlns.oracle.com/bpel/workflow/xpath"
                    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                    xmlns:med="http://schemas.oracle.com/mediator/xpath"
                    xmlns:ids="http://xmlns.oracle.com/bpel/services/IdentityService/xpath"
                    xmlns:bpm="http://xmlns.oracle.com/bpmn20/extensions"
                    xmlns:xdk="http://schemas.oracle.com/bpel/extension/xpath/function/xdk"
                    xmlns:xref="http://www.oracle.com/XSL/Transform/java/oracle.tip.xref.xpath.XRefXPathFunctions"
                    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                    xmlns:ora="http://schemas.oracle.com/xpath/extension"
                    xmlns:socket="http://www.oracle.com/XSL/Transform/java/oracle.tip.adapter.socket.ProtocolTranslator"
                    xmlns:ldap="http://schemas.oracle.com/xpath/extension/ldap"
                    exclude-result-prefixes="xsi xsl ns0 xsd bpws xp20 mhdr bpel oraext dvm hwf med ids bpm xdk xref ora socket ldap">
      <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
      <xsl:variable name="ReceipentID" select="document('../xsd/B2BMarketProperties.xml')"/>
      <xsl:template match="/">
        <ns0:ReceipentIDType>
        <xsl:for-each select="$ReceipentID">
          <ns0:ReceipentID>
            <xsl:value-of select="$ReceipentID"/>
          </ns0:ReceipentID>
          </xsl:for-each>
        </ns0:ReceipentIDType>
      </xsl:template>
    </xsl:stylesheet>
    Following is the XML ( B2BMarketProperties.xml)
    <?xml version="1.0" encoding="UTF-8" ?>
    <ReceipentIDType xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                     xsi:schemaLocation="http://www.example.org B2BMarketProperties.xsd"
                     xmlns="http://www.example.org">
      <ReceipentID>123</ReceipentID>
      <ReceipentID>345</ReceipentID>
    </ReceipentIDType>
    The output i am getting with this code is
    <?xml version="1.0" encoding="UTF-8"?>
    <ns0:ReceipentIDType xmlns:ns0="http://www.example.org">
        <ns0:ReceipentID>123345</ns0:ReceipentID>
    </ns0:ReceipentIDType>
    But, I need output in the following format
    <ns0:ReceipentIDType xmlns:ns0="http://www.example.org">
        <ns0:ReceipentID>123</ns0:ReceipentID>
         <ns0:ReceipentID>345</ns0:ReceipentID>
    </ns0:ReceipentIDType>
    Could you guys let me know what i am doing wrong. Any help would be appreciated.
    Thanks,

    This worked for me :
      <xsl:template match="/">
        <ns0:ReceipentIDType>
          <xsl:for-each select="document('B2BMarketProperties.xml')/*:ReceipentIDType/*:ReceipentID">
            <xsl:variable name="count" select="position()"/>
            <ns0:ReceipentID>
              <xsl:value-of select="document('B2BMarketProperties.xml')/*:ReceipentIDType/*:ReceipentID[$count]"/>
            </ns0:ReceipentID>
          </xsl:for-each>
        </ns0:ReceipentIDType>
      </xsl:template>

  • Problems with reading XML files with ISO-8859-1 encoding

    Hi!
    I try to read a RSS file. The script below works with XML files with UTF-8 encoding but not ISO-8859-1. How to fix so it work with booth?
    Here's the code:
    import java.io.File;
    import javax.xml.parsers.*;
    import org.w3c.dom.*;
    import java.net.*;
    * @author gustav
    public class RSSDocument {
        /** Creates a new instance of RSSDocument */
        public RSSDocument(String inurl) {
            String url = new String(inurl);
            try{
                DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                Document doc = builder.parse(url);
                NodeList nodes = doc.getElementsByTagName("item");
                for (int i = 0; i < nodes.getLength(); i++) {
                    Element element = (Element) nodes.item(i);
                    NodeList title = element.getElementsByTagName("title");
                    Element line = (Element) title.item(0);
                    System.out.println("Title: " + getCharacterDataFromElement(line));
                    NodeList des = element.getElementsByTagName("description");
                    line = (Element) des.item(0);
                    System.out.println("Des: " + getCharacterDataFromElement(line));
            } catch (Exception e) {
                e.printStackTrace();
        public String getCharacterDataFromElement(Element e) {
            Node child = e.getFirstChild();
            if (child instanceof CharacterData) {
                CharacterData cd = (CharacterData) child;
                return cd.getData();
            return "?";
    }And here's the error message:
    org.xml.sax.SAXParseException: Teckenkonverteringsfel: "Malformed UTF-8 char -- is an XML encoding declaration missing?" (radnumret kan vara f�r l�gt).
        at org.apache.crimson.parser.InputEntity.fatal(InputEntity.java:1100)
        at org.apache.crimson.parser.InputEntity.fillbuf(InputEntity.java:1072)
        at org.apache.crimson.parser.InputEntity.isXmlDeclOrTextDeclPrefix(InputEntity.java:914)
        at org.apache.crimson.parser.Parser2.maybeXmlDecl(Parser2.java:1183)
        at org.apache.crimson.parser.Parser2.parseInternal(Parser2.java:653)
        at org.apache.crimson.parser.Parser2.parse(Parser2.java:337)
        at org.apache.crimson.parser.XMLReaderImpl.parse(XMLReaderImpl.java:448)
        at org.apache.crimson.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:185)
        at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:124)
        at getrss.RSSDocument.<init>(RSSDocument.java:25)
        at getrss.Main.main(Main.java:25)

    I read files from the web, but there is a XML tag
    with the encoding attribute in the RSS file.If you are quite sure that you have an encoding attribute set to ISO-8859-1 then I expect that your RSS file has non-ISO-8859-1 character though I thought all bytes -128 to 127 were valid ISO-8859-1 characters!
    Many years ago I had a problem with an XML file with invalid characters. I wrote a simple filter (using FilterInputStream) that made sure that all the byes it processed were ASCII. My problem turned out to be characters with value zero which the Microsoft XML parser failed to process. It put the parser in an infinite loop!
    In the filter, as each byte is read you could write out the Hex value. That way you should be able to find the offending character(s).

  • Read XML file with JSX

    I would like to be able to read an XML file in an InDesign script and create a new document by looping through its nodes and extracting content from them. I've never done this before and I can't seem to find the right information on how to do it. Can someone give me a snippet to get me started? Thanks!

    Read the "Integrating XML into JavaScript" chapter in "JavaScript Tools Guide".
    Below is a script I made a while ago. It can give you idea how to start writing your own script. It reads an xml-file, creates a new document from the template, relinks links listed in the xml-file comparing the width, height and resolution with data in the xml-file.
    // Copyright 2011, «Студия Форма»
    // October 3, 2011
    // Written by Kasyan Servetsky
    // http://www.kasyan.ho.com.ua
    // e-mail: [email protected]
    //==================================== GLOBALS ==========================================
    var gErrMsgArr = [];
    //=======================================================================================
    Main();
    //=================================== FUNCTIONS  =========================================
    function Main() {
        var montage, doc, docFile, component, noErrors, pdfPath, pdfFile, targetPagesLength, destinationFolder;
        var currentFolder = Folder.selectDialog("Выберите текущую папку");  //new Folder("/D/Evgen/");
        if (currentFolder == null) exit();
        var currentFolderPath = currentFolder.absoluteURI + "/";
        var xmlFile = new File(currentFolderPath + "!sforder.xml");
        if (!xmlFile.exists) exit();   
        var outFolderPath = "~/Desktop/Output/";
        var outFolder = new Folder(outFolderPath);
        if (!outFolder.exists) outFolder.create();
        xmlFile.open("r");
        var xmlStr = xmlFile.read();
        xmlFile.close();
        var root = new XML(xmlStr);
        default xml namespace = "http://www.forma-studio.com/order";
        var linksArr = [];
        var componentList = root.xpath("/order/product/components/component");
        var componentsLength = componentList.length();   
        for (var c = 0; c < componentsLength; c++) {
            component = componentList[c];
            linksArr.push({ name : component.images.image.file_name.toString(),
                                width : parseInt(component.images.image.size.width),
                                height : parseInt(component.images.image.size.height),
                                resolution : parseInt(component.images.image.resolution),
        var montageList = root.xpath("/order/product/montages/montage");
        var montagesLength = montageList.length();
        for (var i = 0; i < montagesLength; i++) {
            montage = montageList[i];
            app.scriptPreferences.userInteractionLevel = UserInteractionLevels.neverInteract;       
            app.open(new File(montage.layout_filename));
            doc = app.activeDocument;
            docFile = new File(outFolderPath + montage.result_filename + ".indd");
            doc.save(docFile);
            app.scriptPreferences.userInteractionLevel = UserInteractionLevels.interactWithAll;
            targetPagesLength = parseInt(montage.page_count);
            if (!isNaN(targetPagesLength)) {
                //$.writeln("About to remove pages - " + doc.name + " - " + montage.page_count);
                while (doc.pages.length > targetPagesLength) {
                    doc.pages.lastItem().remove();
            UpdateAllOutdatedLinks(doc);
            noErrors = ProcessDoc(doc, linksArr, currentFolderPath);
            if (noErrors) {
                destinationFolder = new Folder(montage.destination);
                VerifyFolder(destinationFolder);
                pdfPath = montage.destination + "/" + montage.result_filename + ".pdf"
                pdfFile = new File(pdfPath);
                doc.exportFile(ExportFormat.PDF_TYPE, pdfFile, false, "[High Quality Print]");
            doc.close(SaveOptions.YES);
    function ProcessDoc(doc, linksArr, currentFolderPath) {
        var link, linkFile;
        var noErrors = true;
        var links = doc.links;
    //~     $.writeln("--------------------------");
    //~     $.writeln(doc.name);
        for (var i = links.length-1; i >= 0; i--) {
            link = doc.links[i];
            for (var o = 0; o < linksArr.length; o++) {
                if (link.name == linksArr[o].name) {
                    linkFile = new File(currentFolderPath + linksArr[o].name);
                    if (linkFile.exists) {
    //~                     $.writeln("\t" + o + " - " + linkFile.name + " - linkFile.exists");
                        if (CheckLink(link, linksArr[o], doc) == false) noErrors = false;
                        link.relink(linkFile);
                    else {
                        $.writeln(o + " - " + linkFile.name + " - linkFile doesn't exist");
                        noErrors = false;
    //~     $.writeln("--------------------------");
        return noErrors;
    function CheckLink(link, linkObj, doc) {
        var errMessage;   
        var result = true;
        var image = link.parent;
        var actualPpi = image.actualPpi;
        var md = link.linkXmp;
        var reportFilePath = doc.fullName.absoluteURI.replace(/\.indd$/i, ".txt");
        var width = parseInt(md.getProperty("http://ns.adobe.com/exif/1.0/", "exif:PixelXDimension"));
        var height = parseInt(md.getProperty("http://ns.adobe.com/exif/1.0/", "exif:PixelYDimension"));
        if (actualPpi[0] != linkObj.resolution && actualPpi[1] != linkObj.resolution) {
            errMessage = link.name + " - resolution is NOT correct: " + actualPpi[0] + "/" + actualPpi[1] + " ppi instead of " + linkObj.resolution + "\r";
            if (IsInArray(errMessage, gErrMsgArr) == false) {
                gErrMsgArr.push(errMessage);           
                //$.writeln(errMessage);
                WriteToFile(errMessage, reportFilePath);
                result = false;   
        if (height != linkObj.height) {
            errMessage = link.name + " - height is NOT correct: " + height + " pixels instead of " + linkObj.height + "\r";
            if (IsInArray(errMessage, gErrMsgArr) == false) {
                gErrMsgArr.push(errMessage);           
                //$.writeln(errMessage);
                WriteToFile(errMessage, reportFilePath);
                result = false;   
        if (width != linkObj.width) {
            errMessage = link.name + " - width is NOT correct: " + width + " pixels instead of " + linkObj.width + "\r";
            if (IsInArray(errMessage, gErrMsgArr) == false) {
                gErrMsgArr.push(errMessage);           
                //$.writeln(errMessage);
                WriteToFile(errMessage, reportFilePath);
                result = false;   
        return result;
    function UpdateAllOutdatedLinks(doc) {
        var link;
        for (var i = doc.links.length-1; i >= 0; i--) {
            link = doc.links[i];
            if (link.status == LinkStatus.LINK_OUT_OF_DATE) link.update();
    function WriteToFile(text, reportFilePath) {
        file = new File(reportFilePath);
        file.encoding = "UTF-8";
        if (file.exists) {
            file.open("e");
            file.seek(0, 2);
        else {
            file.open("w");
        file.write(text);
        file.close();
    function GetDate() {
        var date = new Date();
        if ((date.getYear() - 100) < 10) {
            var year = "0" + new String((date.getYear() - 100));
        else {
            var year = new String((date.getYear() - 100));
        var dateString = (date.getMonth() + 1) + "/" + date.getDate() + "/" + year + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
        return dateString;
    function ErrorExit(error, icon) {
        alert(error, gScriptName + " - " + gScriptVersion, icon);
        exit();
    function IsInArray(string, arr) {
        for (x in arr) {
            if (string.toLowerCase() == arr[x].toLowerCase()) {
                return true;
        return false;
    function VerifyFolder(folder) {
        if (!folder.exists) {
            var folder = new Folder(folder.absoluteURI);
            var arr1 = new Array();
            while (!folder.exists) {
                arr1.push(folder);
                folder = new Folder(folder.path);
            var arr2 = new Array();
            while (arr1.length > 0) {
                folder = arr1.pop();
                if (folder.create()) {
                    arr2.push(folder);
                } else {
                    while (arr2.length > 0) {
                        arr2.pop.remove();
                    throw "Folder creation failed";

  • Read xml File with counter

    I have a question, but I posted it on the wrong forum. This is the link:
    https://social.msdn.microsoft.com/Forums/en-US/899c8291-70f5-4c1b-abf2-a1a1242e017a/read-xml-file-with-counter?forum=visualstudiogeneral&prof=required

    Hi,
    I have created a program that read an xml file like this:
    <xas>
    <information>
    <list>"12345"</list>
    <version>1.0.0.1</version>
    </information>
    <word><n>0</n><v>test123v</v><a>test123a</a></word>
    <word><n>1</n><v>testv</v><a>testa</a></word>
    </xas>
    I read it to a listview called listview1:
    The MainWindow.xaml:
    <Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="" Height="1220" Width="1017" WindowStartupLocation="Manual" ScrollViewer.HorizontalScrollBarVisibility="Visible" ScrollViewer.CanContentScroll="True" UseLayoutRounding="False" WindowState="Maximized">
    <Grid>
    <ListView x:Name="ListView1" HorizontalAlignment="Left" Height="1220" VerticalAlignment="Top" Width="1017">
    <ListView.View>
    <GridView x:Name="Lijst">
    <GridViewColumn x:Name="Vraag" Header="Vraag" DisplayMemberBinding="{Binding Vraag}">
    </GridViewColumn>
    <GridViewColumn x:Name="Antwoord" Header="Antwoord" DisplayMemberBinding="{Binding Antwoord}">
    </GridViewColumn>
    </GridView>
    </ListView.View>
    </ListView>
    </Grid>
    </Window>
    And this is MainWindow.xaml.vb:
    Imports System.IO
    Imports System.Reflection.Assembly
    Imports System.Xml
    Imports System.Data
    Class MainWindow
    Dim VraagListBox As New ListBox
    Dim AntwoordListBox As New ListBox
    Dim Hoofdmap As String = GetExecutingAssembly().Location
    Dim Bestand As String
    Private Sub MainWindow_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
    'RUNNEN MAAR!!!!
    'Het bestand vinden in de commandline argumenten
    Dim args() As String = System.Environment.GetCommandLineArgs()
    Dim Teller As Integer = "0"
    For Each arg As String In args
    If Teller = "1" Then
    Bestand = arg
    Else
    Teller = Teller + "1"
    End If
    Next
    Bestand = "D:\Alles voor school!\Alles voor school!\Vakken\Stepping Stones\DATA1\Hoofdstuk 1\Leerlijsten\Hoofdstuk 1 Grammer 1.xas"
    'Welk bestand? Set de title
    Me.Title = Path.GetFileName(Bestand) & " - ListViewer (V.1.0.0.6)"
    If Bestand <> "" Then
    'Vragen en antwoorden toevoegen in de kolommen
    If Path.GetExtension(Bestand) = ".xas" Then
    Dim orderInfo = XElement.Load(Bestand)
    For Each entry As XElement In orderInfo...<word>
    Dim thisOrder As New Order
    With thisOrder
    .Vraag = entry...<v>.Value
    .Antwoord = entry...<a>.Value
    End With
    ListView1.Items.Add(thisOrder)
    Next
    'Virtuele vraaglistbox toevoegen = kolom Vraag van LisView1
    Dim orderInfoVraag = XElement.Load(Bestand)
    For Each entry As XElement In orderInfoVraag...<word>
    Dim thisOrderVraag As New VraagClass
    With thisOrderVraag
    .Vraag = entry...<v>.Value
    End With
    VraagListBox.Items.Add(thisOrderVraag)
    Next
    'Virtuele antwoordlistbox toevoegen = kolom Antwoord van LisView1
    Dim orderInfoAntwoord = XElement.Load(Bestand)
    For Each entry As XElement In orderInfoAntwoord...<word>
    Dim thisOrderAntwoord As New AntwoordClass
    With thisOrderAntwoord
    .Antwoord = entry...<a>.Value
    End With
    AntwoordListBox.Items.Add(thisOrderAntwoord)
    Next
    'Check wat er fout is aan het bestand, en geef een melding
    Else
    MessageBox.Show("Er is een verkeerde extentie geselecteerd, namelijk: " & Path.GetExtension(Bestand) & ".", "Verkeerde extentie - ListViewer", MessageBoxButton.OK, MessageBoxImage.Error)
    Me.Close()
    End If
    Else
    If Bestand = "" Then
    MessageBox.Show("Je hebt geen bestand geselecteerd", "Geen bestand geselecteerd - ListViewer", MessageBoxButton.OK, MessageBoxImage.Error)
    Me.Close()
    Else
    MessageBox.Show("Er is iets misgegaan met het laden van het bestand, probeer het later opnieuw", "Onbekende error - ListViewer", MessageBoxButton.OK, MessageBoxImage.Error)
    Me.Close()
    End If
    End If
    End Sub
    Private Sub ListView1_MouseDoubleClick(sender As Object, e As MouseButtonEventArgs) Handles ListView1.MouseDoubleClick
    Directory.CreateDirectory(Path.GetTempPath & "110% Soft\ListViewer 1.0.0.6\" & Path.GetFileName(Bestand))
    Dim SchrijfVraag As New StreamWriter(Path.GetTempPath & "110% Soft\ListViewer 1.0.0.6\Word.txt")
    Dim SchrijfFile As New StreamWriter(Path.GetTempPath & "110% Soft\ListViewer 1.0.0.6\File.txt")
    SchrijfVraag.WriteLine(ListView1.SelectedIndex)
    SchrijfFile.WriteLine(Bestand)
    SchrijfVraag.Close()
    SchrijfFile.Close()
    Dim WoordenScherm As ViewWord
    WoordenScherm = New ViewWord()
    WoordenScherm.ShowDialog()
    End Sub
    End Class
    ViewWord.xaml is:
    <Window x:Class="ViewWord"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="ViewWord" Height="155" Width="1017" ResizeMode="NoResize" SizeToContent="WidthAndHeight" Topmost="True" WindowStartupLocation="CenterScreen">
    <Grid>
    <Label x:Name="VraagLabel" Content="Vraag:" HorizontalAlignment="Left" Margin="23,11,0,0" VerticalAlignment="Top" Width="106"/>
    <TextBox x:Name="VraagTextBox" HorizontalAlignment="Left" Height="24" Margin="134,13,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="743" />
    <Label x:Name="AntwoordLabel" Content="Antwoord:" HorizontalAlignment="Left" Margin="23,42,0,0" VerticalAlignment="Top" Width="106"/>
    <TextBox x:Name="AntwoordTextBox" HorizontalAlignment="Left" Height="24" Margin="134,44,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="743"/>
    <Button x:Name="VraagAanpassenButton" Content="Aanpassen" HorizontalAlignment="Left" Margin="882,15,0,0" VerticalAlignment="Top" Width="107"/>
    <Button x:Name="AntwoordAanpassenButton" Content="Aanpassen" HorizontalAlignment="Left" Margin="882,44,0,0" VerticalAlignment="Top" Width="107"/>
    <Label x:Name="VraagNummerLabel" Content="Vraagnummer:" HorizontalAlignment="Left" Margin="23,72,0,0" VerticalAlignment="Top" Width="106"/>
    <TextBox x:Name="VraagNummerTextBox" HorizontalAlignment="Left" Height="24" Margin="134,74,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="743"/>
    <Button x:Name="VraagNummerAanpassenButton" Content="Aanpassen" HorizontalAlignment="Left" Margin="882,74,0,0" VerticalAlignment="Top" Width="107"/>
    </Grid>
    </Window>
    In VraagTextBox must come the entry <word><v>test123v</v></word>, in AntwoordTextBox must come the entry <word><a>test123a</a></word>, and in VraagNummerTextBox must come the entry <word><n>0</n></word>
    This is the code to fix that (ViewWord.xaml.vb):
    Imports System.IO
    Public Class ViewWord
    Private Structure AntwoordVraag
    Public Vraag As String
    Public Antwoord As String
    End Structure
    Private Sub ViewWord_Initialized(sender As Object, e As EventArgs) Handles Me.Initialized
    End Sub
    Private Sub AntwoordAanpassenButton_Click(sender As Object, e As RoutedEventArgs) Handles AntwoordAanpassenButton.Click
    Dim Vraagnummer As String
    Dim Bestandsnaam As String
    Dim LeesVraag As New StreamReader(Path.GetTempPath & "110% Soft\ListViewer 1.0.0.6\Word.txt")
    Dim LeesFile As New StreamReader(Path.GetTempPath & "110% Soft\ListViewer 1.0.0.6\File.txt")
    Vraagnummer = LeesVraag.ReadLine()
    Bestandsnaam = LeesFile.ReadLine()
    LeesVraag.Close()
    LeesFile.Close()
    MessageBox.Show(Vraagnummer)
    Dim teller As Integer = 0
    Dim orderInfo = XElement.Load(Bestandsnaam)
    If teller = Vraagnummer Then
    VraagNummerTextBox.Text = orderInfo...<word>...<n>.Value
    VraagTextBox.Text = orderInfo...<word>...<v>.Value
    AntwoordTextBox.Text = orderInfo...<word>...<a>.Value
    Else
    teller = teller + 1
    End If
    End Sub
    End Class
    But the result isn't:
    VraagTextBox.Text = testv
    AntwoordTextBox.Text = testa
    NummerTextBox.Text = 1 
    if i click on the number 2 of the listview (index = 1)
    How can i fix it?

  • Reading xml file with sax parser: unknown protocol: c

    Hi,
    I've been googling around, and the best I can find is that the file name:
    File test = new File("lib/test/parseTest/validate-test.xml");should be a url:
    File test = new File("File://lib/test/parseTest/validate-test.xml");but I'm working on a linux machine and can't put "File://c:/pathToFile/file.xml"
    Also, I did some testing and I can read a small xml file with just a few elements, but on large complex files, I get that error.
    anyone ever run into this before?
    bp
    Edited by: badperson on Nov 1, 2008 2:19 PM

    badperson wrote:
    I've been googling around, and the best I can find is that the file name:
    File test = new File("lib/test/parseTest/validate-test.xml");should be a url:
    File test = new File("File://lib/test/parseTest/validate-test.xml");
    No, that's wrong. The parameter for that constructor is a file path (relative or absolute). Not a URL. You must have misunderstood whatever you read.
    but I'm working on a linux machine and can't put "File://c:/pathToFile/file.xml"What kind of a Linux machine is this which has a C drive? You must have misunderstood whoever told you to do that.

  • Create xml file with values from context

    Hi experts!
    I am trying to implement a WD application that will have some input fields, the value of those input fields will be used to create an xml file with a certain format and then sent to a certain application.
    Apart from this i want to read an xml file back from the application and then fill some other context nodes with values from the xml file.
    Is there any standard used code to do this??
    If not how can i do this???
    Thanx in advance!!!
    P.S. Points will be rewarded to all usefull answers.
    Edited by: Armin Reichert on Jun 30, 2008 6:12 PM
    Please stop this P.S. nonsense!

    Hi,
    you need to create three util class for that:-
    XMLHandler
    XMLParser
    XMLBuilder
    for example in my XML two tag item will be there e.g. Title and Organizer,and from ur WebDynpro view you need to pass value for the XML tag.
    And u need to call buildXML()function of builder class to generate XML, in that i have passed bean object to get the values of tags. you need to set the value in bean from the view ui context.
    Code for XMLBuilder:-
    Created on Apr 4, 2006
    Author-Anish
    This class is to created for having function for to build XML
    and to get EncodedXML
      and to get formated date
    package com.idb.events.util;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import com.idb.events.Event;
    public class XMLBuilder {
    This attribute represents the XML version
         private static final double VERSION_NUMBER = 1.0;
    This attribute represents the encoding
         private static final String ENCODING_TYPE = "UTF-16";
         /*Begin of Function to buildXML
    return: String
    input: Event
         public String buildXML(Event event) {
              StringBuffer xmlBuilder = new StringBuffer("<?xml version=\"");
              xmlBuilder.append(VERSION_NUMBER);
              xmlBuilder.append("\" encoding=\"");
              xmlBuilder.append(ENCODING_TYPE);
              xmlBuilder.append("\" ?>");
              xmlBuilder.append("<event>");
              xmlBuilder.append(getEncodedXML(event.getTitle(), "title"));
              xmlBuilder.append(getEncodedXML(event.getOrganizer(), "organizer"));
              xmlBuilder.append("</event>");
              return xmlBuilder.toString();
         /End of Function to buildXML/
         /*Begin of Function to get EncodedXML
    return: String
    input: String,String
         public String getEncodedXML(String xmlString, String tag) {
              StringBuffer begin = new StringBuffer("");
              if ((tag != null) || (!tag.equalsIgnoreCase("null"))) {
                   begin.append("<").append(tag).append(">");
                   begin.append("<![CDATA[");
                   begin.append(xmlString).append("]]>").append("</").append(
                        tag).append(
                        ">");
              return begin.toString();
         /End of Function to get EncodedXML/
         /*Begin of Function to get formated date
    return: String
    input: Date
         private final String formatDate(Date inputDateStr) {
              String date;
              try {
                   SimpleDateFormat simpleDateFormat =
                        new SimpleDateFormat("yyyy-MM-dd");
                   date = simpleDateFormat.format(inputDateStr);
              } catch (Exception e) {
                   return "";
              return date;
         /End of Function to get formated date/
    Code for XMLParser:-
    Created on Apr 12, 2006
    Author-Anish
    This is a parser class
    package com.idb.events.util;
    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    import org.xml.sax.XMLReader;
    import com.idb.events.Event;
    import com.sap.tc.webdynpro.progmodel.api.IWDMessageManager;
    public class XMLParser {
    Enables namespace functionality in parser
         private final boolean isNameSpaceAware = true;
    Enables validation in parser
         private final boolean isValidating = true;
    The SAX parser used to parse the xml
         private SAXParser parser;
    The XML reader used by the SAX parser
         private XMLReader reader;
    This method creates the parser to parse the user details xml.
         private void createParser()
              throws SAXException, ParserConfigurationException {
              // Create a JAXP SAXParserFactory and configure it
              SAXParserFactory saxFactory = SAXParserFactory.newInstance();
              saxFactory.setNamespaceAware(isNameSpaceAware);
              saxFactory.setValidating(isValidating);
              // Create a JAXP SAXParser
              parser = saxFactory.newSAXParser();
              // Get the encapsulated SAX XMLReader
              reader = parser.getXMLReader();
              // Set the ErrorHandler
    This method is used to collect the user details.
         public Event getEvent(
              String newsXML,
              XMLHandler xmlHandler,
              IWDMessageManager mgr)
              throws SAXException, ParserConfigurationException, IOException {
              //create the parser, if not already done
              if (parser == null) {
                   this.createParser();
              //set the parser handler to extract the
              reader.setErrorHandler(xmlHandler);
              reader.setContentHandler(xmlHandler);
              InputSource source =
                   new InputSource(new ByteArrayInputStream(newsXML.getBytes()));
              reader.parse(source);
              //return the results of the parse           
              return xmlHandler.getEvent(mgr);
    Code for XMLHandler:-
    Created on Apr 12, 2006
    Author-Anish
    This is a parser class
    package com.idb.events.util;
    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    import org.xml.sax.XMLReader;
    import com.idb.events.Event;
    Created on Apr 12, 2006
    Author-Anish
    *This handler class is created to have constant value for variables and function for get events,
        character values for bean variable,
        parsing thr date ......etc
    package com.idb.events.util;
    import java.sql.Timestamp;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Locale;
    import org.xml.sax.Attributes;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    import org.xml.sax.helpers.DefaultHandler;
    import java.util.*;
    import com.idb.events.Event;
    import com.sap.tc.webdynpro.progmodel.api.IWDMessageManager;
    public class XMLHandler extends DefaultHandler {
         private static final String TITLE = "title";
         private static final String ORGANIZER = "organizer";
         IWDMessageManager manager;
         private Event events;
         private String tagName;
         public void setManager(IWDMessageManager mgr) {
              manager = mgr;
    This function is created to get events
         public Event getEvent(IWDMessageManager mgr) {
              manager = mgr;
              return this.events;
    This function is created to get character for setting values through event's bean setter method
         public void characters(char[] charArray, int startVal, int length)
              throws SAXException {
              String tagValue = new String(charArray, startVal, length);
              if (TITLE.equals(this.tagName)) {
                   this.events.setTitle(tagValue);
              if (ORGANIZER.equals(this.tagName)) {
                   String orgName = tagValue;
                   try {
                        orgName = getOrgName(orgName);
                   } catch (Exception ex) {
                   this.events.setOrganizer(orgName);
    This function is created to parse boolean.
         private final boolean parseBoolean(String inputBooleanStr) {
              boolean b;
              if (inputBooleanStr.equals("true")) {
                   b = true;
              } else {
                   b = false;
              return b;
    This function is used to call the super constructor.
         public void endElement(String uri, String localName, String qName)
              throws SAXException {
              super.endElement(uri, localName, qName);
         /* (non-Javadoc)
    @see org.xml.sax.ErrorHandler#fatalError(org.xml.sax.SAXParseException)
    This function is used to call the super constructor.
         public void fatalError(SAXParseException e) throws SAXException {
              super.fatalError(e);
    This function is created to set the elements base on the tag name.
         public void startElement(
              String uri,
              String localName,
              String qName,
              Attributes attributes)
              throws SAXException {
              this.tagName = localName;
              if (ROOT.equals(tagName)) {
                   this.events = new Event();
         public static void main(String a[]) {
              String cntry = "Nigeria";
              XMLHandler xml = new XMLHandler();
              ArrayList engList = new ArrayList();
              engList = xml.getCountries();
              ArrayList arList = xml.getArabicCountries();
              int engIndex = engList.indexOf(cntry);
              System.out.println("engIndex  :: " + engIndex);
              String arCntryName = (String) arList.get(engIndex);
              System.out.println(
                   ">>>>>>>>>>>>>>>>>>>>" + xml.getArabicCountryName(cntry));
    Hope that may help you.
    If need any help , you are most welcome.
    Regards,
    Deepak

Maybe you are looking for