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?

Similar Messages

  • 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

  • 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 LINQ

    hello all,
    I've this XML file:
    <?xml version="1.0" standalone="yes"?>
    <Configurations>
    <PageConfigurations softwareCode="63720415" softwareVersion="07" />
    <Page pageName="PAGE1">
    <description>DESC1</description>
    <Param>
    <name>TaskMulti_guc</name>
    <address>1128203</address>
    <nameType>C</nameType>
    <size>1</size>
    <offset>0</offset>
    <format>Hexadecimal</format>
    <description>description</description>
    <adminReadonly>false</adminReadonly>
    <userReadonly>true</userReadonly>
    <byteNumber>4</byteNumber>
    <gainK1>1</gainK1>
    <gainK2>1</gainK2>
    <offsetScale>0</offsetScale>
    <switchName />
    <switchAddress />
    <switchType />
    <switchSize>1</switchSize>
    <switchOffset>0</switchOffset>
    <switchByteNumber>4</switchByteNumber>
    <switchValue>0</switchValue>
    <switchTime>Before</switchTime>
    <switchReset>false</switchReset>
    <debugName />
    <debugAddress />
    <debugType />
    <debugSize>1</debugSize>
    <debugOffset>0</debugOffset>
    </Param>
    <Param>
    <name>TempNum_guh</name>
    <address>1124743</address>
    <nameType>H</nameType>
    <size>1</size>
    <offset>0</offset>
    <format>Hexadecimal</format>
    <description>description</description>
    <adminReadonly>false</adminReadonly>
    <userReadonly>true</userReadonly>
    <byteNumber>4</byteNumber>
    <gainK1>1</gainK1>
    <gainK2>1</gainK2>
    <offsetScale>0</offsetScale>
    <switchName />
    <switchAddress />
    <switchType />
    <switchSize>1</switchSize>
    <switchOffset>0</switchOffset>
    <switchByteNumber>4</switchByteNumber>
    <switchValue>0</switchValue>
    <switchTime>Before</switchTime>
    <switchReset>false</switchReset>
    <debugName />
    <debugAddress />
    <debugType />
    <debugSize>1</debugSize>
    <debugOffset>0</debugOffset>
    </Param>
    <Param>
    <name>vMylifeSignal_guc</name>
    <address>1131388</address>
    <nameType>C</nameType>
    <size>1</size>
    <offset>0</offset>
    <format>Hexadecimal</format>
    <description>description</description>
    <adminReadonly>false</adminReadonly>
    <userReadonly>true</userReadonly>
    <byteNumber>4</byteNumber>
    <gainK1>1</gainK1>
    <gainK2>1</gainK2>
    <offsetScale>0</offsetScale>
    <switchName />
    <switchAddress />
    <switchType />
    <switchSize>1</switchSize>
    <switchOffset>0</switchOffset>
    <switchByteNumber>4</switchByteNumber>
    <switchValue>0</switchValue>
    <switchTime>Before</switchTime>
    <switchReset>false</switchReset>
    <debugName />
    <debugAddress />
    <debugType />
    <debugSize>1</debugSize>
    <debugOffset>0</debugOffset>
    </Param>
    </Page>
    <Page pageName="PAGE2">
    <description>DESC2</description>
    <Param>
    <name>TaskMulti_guc</name>
    <address>1128203</address>
    <nameType>C</nameType>
    <size>1</size>
    <offset>0</offset>
    <format>Hexadecimal</format>
    <description>description</description>
    <adminReadonly>false</adminReadonly>
    <userReadonly>true</userReadonly>
    <byteNumber>4</byteNumber>
    <gainK1>1</gainK1>
    <gainK2>1</gainK2>
    <offsetScale>0</offsetScale>
    <switchName />
    <switchAddress />
    <switchType />
    <switchSize>1</switchSize>
    <switchOffset>0</switchOffset>
    <switchByteNumber>4</switchByteNumber>
    <switchValue>0</switchValue>
    <switchTime>Before</switchTime>
    <switchReset>false</switchReset>
    <debugName />
    <debugAddress />
    <debugType />
    <debugSize>1</debugSize>
    <debugOffset>0</debugOffset>
    </Param>
    <Param>
    <name>TaskMulti_guc</name>
    <address>1128203</address>
    <nameType>C</nameType>
    <size>1</size>
    <offset>0</offset>
    <format>Hexadecimal</format>
    <description>description</description>
    <adminReadonly>false</adminReadonly>
    <userReadonly>true</userReadonly>
    <byteNumber>4</byteNumber>
    <gainK1>1</gainK1>
    <gainK2>1</gainK2>
    <offsetScale>0</offsetScale>
    <switchName />
    <switchAddress />
    <switchType />
    <switchSize>1</switchSize>
    <switchOffset>0</switchOffset>
    <switchByteNumber>4</switchByteNumber>
    <switchValue>0</switchValue>
    <switchTime>Before</switchTime>
    <switchReset>false</switchReset>
    <debugName />
    <debugAddress />
    <debugType />
    <debugSize>1</debugSize>
    <debugOffset>0</debugOffset>
    </Param>
    </Page>
    <Page pageName="PAGE3">
    <description>DESC3</description>
    <Param>
    <name>TaskMulti_guc</name>
    <address>1128203</address>
    <nameType>C</nameType>
    <size>1</size>
    <offset>0</offset>
    <format>Hexadecimal</format>
    <description>description</description>
    <adminReadonly>false</adminReadonly>
    <userReadonly>true</userReadonly>
    <byteNumber>4</byteNumber>
    <gainK1>1</gainK1>
    <gainK2>1</gainK2>
    <offsetScale>0</offsetScale>
    <switchName />
    <switchAddress />
    <switchType />
    <switchSize>1</switchSize>
    <switchOffset>0</switchOffset>
    <switchByteNumber>4</switchByteNumber>
    <switchValue>0</switchValue>
    <switchTime>Before</switchTime>
    <switchReset>false</switchReset>
    <debugName />
    <debugAddress />
    <debugType />
    <debugSize>1</debugSize>
    <debugOffset>0</debugOffset>
    </Param>
    </Page>
    </Configurations>
    with this class:
    public class Page
    public string PageName { get; set; }
    public string Description { get; set; }
    public List<Param> List = new List<Param>();
    public class Param
    public string Name { get; set; }
    public string Address { get; set; }
    public string Format { get; set; }
    public string Description { get; set; }
    How can I read this file with LINQ (I'm no expert) for fill correctly my object ?
    Thanks in advance.
    Stefano

    Please refer to the following sample code:
    XDocument doc = XDocument.Load("c:\data1.xml");
    List<Page> pages = new List<Page>();
    var pageElems = doc.Root.Elements("Page");
    foreach (var page in pageElems)
    Page pageObj = new Page();
    pageObj.PageName = page.Attribute("pageName").Value;
    pageObj.Description = page.Element("description").Value;
    pageObj.List = new List<Param>();
    var paramElems = page.Elements("Param");
    foreach(var paramElem in paramElems)
    Param paramObj = new Param();
    paramObj.Address = paramElem.Element("address").Value;
    paramObj.Description = paramElem.Element("description").Value;
    pageObj.List.Add(paramObj);
    pages.Add(pageObj);
    The code adds the Page objects to the pages list.
    Please remember to close your threads by marking all helpful posts as answer and then start a new thread if you have a new question.

  • 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.

  • To read XML file with DTD in SSIS

    Hi,
    My SISS package needs to read .mak file and store it in a sql tables.
    I am receiving xml file content in mak file extension with DTD. So I couldn't read through XML source shows error DTD is prohibited in this document. After removing DTD by manually, the xml file has multiple outputs.
    Please guide me how to remove DTD by coding and also I don't have xsd and xsl file for this only mak file.
    Thanks.

    Thanks Visakh for your answer.
    I have tried in XML task which described in the thread. But I couldn't remove DTD file, I am getting following error,
    [XML Task] Error: An error occurred with the following error message: "Could not find a part of the path 'C:\Program Files (x86)\FAST\Builder\bin\makefile.dtd'.".
    As I said before I am receiving in .mak file extension. The beginning of file content is like below,
    <?xml version='1.0'?>
    <!DOCTYPE makefile SYSTEM "file:///C:/ProgramFiles
    (x86)/FAST/Builder/bin/makefile.dtd"[
    <!ENTITY % default-content-type "'text/html'">
    <!ENTITY prjdir "G:\cdrom\Employees_2014_02">
    <!ENTITY imgdir "G:\images\forms\gifs">
    <!ENTITY foddir "G:\SOFT\FORMS CD\Feb14">
    <!ENTITY ccdir "Y:\Content">
    ]>
    <makefile>
    &fsysdse;
    <content-collection id="b1" title="Employers and Employees" filename="&ccdir;\Employees_2014_02.nfo" password=""> ....
    After replace all variable (prjdir,imgdir,fodder,ccdir) into values specified in the entity tag, I removed above underlined part - so the xml file is ready without DTD part and able to use in
    XML source. I have received 6 outputs from XML source.
    My question is how to do this manual work in SSIS? It’s not only one file, so many files needs to updated SQL tables automatically so everything should be done by coding.
    Please guide me in which way I can achieve this?
    If you want to do this in SSIS
    one way is to use Script Task to parse the file and remove the DTD part.
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • 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 a file with a variable=counter : NAMEFILE001,NAMEFILE002..

    Hello,
    I would need your councils.
    I can read a logical file on my server(logical example of name: NAMEFILE) with function FILE_GET_NAME.
    But I would like to be able to read a file with a counter i.e.
    the first time: to read NAMEFILE001;
    the second time read NAMEFILE002;
    the third time read NAMEFILER003...
    How made you that?
    With function FILENAME_EXIT _?
    But, where do I put the variable = counter? In a table...?
    Thank you in advance of your answer
    Servane

    Hi Servane,
    You could also do the following:
    in transaction FILE you set up the physical path name as follows:
    /<i>path</i>/.../<FILENAME><PARAM_1>
    then you call the function FILE_GET_NAME:
      CALL FUNCTION 'FILE_GET_NAME'
           EXPORTING
             LOGICAL_FILENAME        = W_LOGICAL_FILENAME
             PARAMETER_1             = W_FILENUMBER
          IMPORTING
               FILE_NAME               = THEFILE
           EXCEPTIONS
                FILE_NOT_FOUND          = 1
                OTHERS                  = 2.
    This will equally construct the name/counter as you wish.
    AND, if I am not wrong, since the system does it, you will not have to worry about putting the last counter value away in the DB.
    cheers,
    Phil
    Message was edited by: Phillip Morgan

  • 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

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

  • XML-file with prefix in Java importing

    Hello,
    I have one XML-file with prefix "wf" like this:
       <wf:data>
               <wf:name>NAME</wf:name>
               <wf:description/>
               <wf:creation_time>0001-01-01T00:00:00</wf:creation_time>
               <wf:user wf:ref=""/>
               <wf:properties/>
       </wf:data>the Java-Code like this:
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
              factory.setNamespaceAware(false);
              XPath xpath = XPathFactory.newInstance().newXPath();
              String expression = "./data/name/text()";
              InputSource inputSource = new InputSource("workflow.xml");
                    String result = xpath.evaluate(expression, inputSource);the Java-Code works well, if the prefix does not exist, otherwise I could not get any result. Could somebody please help me?
    Thank you
    Sunny

    I have defined the namespaceI didn't see that in your original post.
    I notice that your XPath expression doesn't include the namespace prefixes and you don't tell it how to map the prefixes to the namespace URIs. I am not sure whether calling factory.setNamespaceAware(false) makes it unnecessary to do that. I wouldn't count on it.

  • FM to read XML files from Application server in ECC5.0

    Hi All,
    We need to pick up an XML file from Application server/FTP server. The requirement is to parse the XML file and process it to create material master. SAP provides standard function modules to read XML files.
    Now we need to read the XML file contents of MM01 and upload into SAP Data Base through BAPI
    I need to know about the Function modules to read XML files from Application Server and also about the FM's that will update the Date base tables with the data obtained form XML files.
    Regards
    Prathima

    Parsing XML data:
    http://help.sap.com/saphelp_nw04/helpdata/en/86/8280ba12d511d5991b00508b6b8b11/frameset.htm
    or alternatively check out ABAP online help for "CALL TRANSFORMATION".
    For creating the material master look at BAPI_STANDARDMATERIAL_CREATE.
    Thomas

  • How can I save a XML file with JAXP1.1?

    Dear All.
    I write a program to create XML file with DOM model, but I can't know how to save it? My environment is JAXP1.1 and JDK1.3.1,I has been required not use other XML parser toolkits,only JAXP1.1.
    How can I do? thank you.
    Many person give me a idea the com.sun.xml.tree.XmlDocument, but I can't find the class in API document or JAXP1.1's packages. why?
    what is it? How can i use it?
    thank you very much.

    The way to save an XML Document is using a Transformer.
    To have access to a transformer use the packages :
    import javax.xml.transform.*;
    import javax.xml.transform.dom.*;
    import javax.xml.transform.stream.*;
    Then for saving your Document Object (named dXml) get a Transformer Object with the TransformerFactory Object :
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer();
    Now you have got your Transformer Object, to save your Document Object use the method :
    Document dXml = getMyDocument(); // this is your Document Object.
    OutputStream osSave = getMySaveStream(); // this the OutputStream you need to save your Document.
    try
    t.transform(new DomSource(dXml), new StreamResult(new OutputStreamWriter(osSave)));
    finally
    osSave.close();
    And your Document was now saved.

  • Generation of Xml file with java output

    Hi i m new to xml and java combination. I have a name value pair kind of output returning from java program. I want to generate the new xml file with the data. Could some one help me out in generating xml file with the data. Could anyone send me the java code that does this task.

    Let me know which parser are you using currently for reading xml files so that i assist you. For now, you can refer to STAX Parser API under this link
    http://java.sun.com/webservices/docs/1.6/tutorial/doc/SJSXP3.html

  • Create XML file with worksheet's dynamically assigned through XSLT

    Hi all
    I have a requirement to create a xml file with worksheets dynamically created based on a field value in the internal table .
    I have all my values in internal table,  and am calling the transformation from bsp application.
    Say the internal table has field dataxyz, for every change in value in this field dataxyz  i need to create separate worksheet and populate that sheet with some corresponding values .
    please guide me how to create worksheet dynamically.
    thanks in advance.
    Bharathy
    Edited by: elam.bharathy on May 16, 2011 6:51 AM

    Can you use a schema when we compose XML doc from Database tables?
    Actually, I'm using SQL Server (sorry, wrong forum). But, I thought a Java tool would have a solution for me.

Maybe you are looking for