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.

Similar Messages

  • How to Create XML file with SAX parser instead of DOM parser

    HI ALL,
    I am in need of creating an XML file by SAX parser ONLY. As far as my knowledge goes, we can use DOM for such purpose(by using createElement, creatAttribute ...). Can anyone tell me, is there any way to create an XML file using SAX Parser only. I mean, I just want to know whether SAX provides any sort of api for Creatign an element, attribute etc. I know that SAX is for event based parsing. But my requirement is to create an XML file from using only SAX parser.
    Any help would be appreciated
    Thanx in advance
    Kaushik

    Hi,
    You must write a XMLWriter class yourself, and that Class extends DefaultHandle ....., the overwrite the startElement(url, localName, qName, attributeList), startDocument(), endElement().....and so on.
    in startElement write your own logic about how to create a new element and how to create a Attribute list
    in startDocument write your own logic about how to build a document and encodeType, dtd....
    By using:
    XMLWriter out = new XMLWriter()
    out.startDocument();
    Attribute attr1 = new Atribute();
    attr1.add("name", "value");
    out.startElement("","","Element1", attr1);
    Attribute attr2 = new Atribute();
    attr2.add("name", "value");
    out.startElement("","","Element2", attr2);
    out.endElement("","","Element2");
    out.endElement("","","Element1");
    out.endDocument();

  • Buiding xml file using SAX parser of JAXP

    Please send me xml building using the sax parser.This is the urgent requirement ,iam not geeting how to solve this problem.so please anybody can help with one best example

    You don't build an XML file with a parser. A parser reads an XML file and converts it to some internal representation. Try reading this tutorial:
    http://java.sun.com/xml/jaxp/dist/1.1/docs/tutorial/

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

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

  • Edit an XML file with SAX

    Dear all, I am so confused�.
    I have been trying for the last few days to understand how sax works� The only thing I understood is:
    DefaultHandler handler = new Echo01();
    SAXParserFactory factory = SAXParserFactory.newInstance();
            try {
                out = new OutputStreamWriter(System.out, "UTF8");
                SAXParser saxParser = factory.newSAXParser();
                saxParser.parse(file , handler);
            } catch (Throwable t) {
                t.printStackTrace();
            System.exit(0);
        }Ok, I assign the SAXParser the xml file and a handler. The parser parses and throws events that the handler catches. By implementing some handler interface or overriding the methods of an existing handler (e.g DeafultHandler class) I get to do stuff�
    But still, suppose I have implement startElement() method of DefaultHandler class and I know that the pointer is currently placed on an element e.g. <name>bob</name>. How do I get the value of the element, and if I manage to do that, how can I replace�bob� with �tom�?
    I would really appreciate any help given� just don�t recommend http://java.sun.com/webservices/jaxp/dist/1.1/docs/tutorial/ because although there are interesting staff in there, it does not solve my problem�

    Maybe SAX is not the right tool for you.
    With SAX, you implement methods like startElement and characters that get called as XML data is encountered by the parser. If you want to catch it or not, the SAX parser does not care. In your case, the "bob" part will be passed in one or more calls to characters. To safely process the data, you need to do something like build a StringBuffer or StringBuilder in the constructor of the class, and then in the startElement, if the name is one you want to read, set the length to zero. In the characters method, append the data to the StringBuilder or StringBuffer. In the endElement, do a toString to keep the data wherever you want.
    This works for simple XML, but may need to be enhanced if you have nested elements with string values that contain other elements.
    On the other hand, if your file is not huge, you could use DOM. With DOM, (or with JDOM, and I would expect with Dom4J -- but I have only used the first two) you do a parse and get a Document object with the entire tree. That allows you to easily (at least it is easy once you figure out how to do it) find a node like the "name" element and change the Text object that is its child from a value of "bob" to "tom". With DOM, you can then serialize the modified Document tree and save it as an XML file. SAX does not have any way to save your data. That burden falls to you entirely.
    Dave Patterson

  • 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

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

  • 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

  • SAX: How to create new XML file using SAX parser

    Hi,
    Please anybody help me to create a XML file using the Packages in the 5.0 pack of java. I have successfully created it reading the tag names and values from database using DOM but can i do this using SAX.
    I am successful to read XML using SAX, now i want to create new XML file for some tags and its values using SAX.
    How can i do this ?
    Sachin Kulkarni

    SAX is a parser, not a generator.Well,
    you can use it to create an XML file too. And it will take care of proper encoding, thus being much superior to a normal textwriter:
    See the following code snippet (out is a OutputStream):
    PrintWriter pw = new PrintWriter(out);
          StreamResult streamResult = new StreamResult(pw);
          SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance();
          //      SAX2.0 ContentHandler.
          TransformerHandler hd = tf.newTransformerHandler();
          Transformer serializer = hd.getTransformer();
          serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");//
          serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"pdfBookmarks.xsd");
          serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"http://schema.inplus.de/pdf/1.0");
          serializer.setOutputProperty(OutputKeys.METHOD,"xml");
          serializer.setOutputProperty(OutputKeys.INDENT, "yes");
          hd.setResult(streamResult);
          hd.startDocument();
          //Get a processing instruction
          hd.processingInstruction("xml-stylesheet","type=\"text/xsl\" href=\"mystyle.xsl\"");
          AttributesImpl atts = new AttributesImpl();
          atts.addAttribute("", "", "someattribute", "CDATA", "test");
          atts.addAttribute("", "", "moreattributes", "CDATA", "test2");
           hd.startElement("", "", "MyTag", atts);
    String curTitle = "Something inside a tag";
              hd.characters(curTitle.toCharArray(), 0, curTitle.length());
        hd.endElement("", "", "MyTag");
          hd.endDocument();
    You are responsible for proper nesting. SAX takes care of encoding.
    Hth
    ;-) stw

  • 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";

  • How to generate Java objects from XML files with out  scema compilation

    Dear participants,
    My name is Raghavendra , i have a requirement of reading XML files Dynamically and parse them and create java types for manipulation . i will not be provided with sxd files (no schema compilation )coz no one knows how many types of structures are there. i want a generic solution. Please Help.
    Thanks ,
    Raghavendra Ach
    you can mail me to " [email protected]"

    georgemc wrote:
    You could also look at something like Apache Digester, which will parse your XML and populate Java objects with the data. A slightly steeper learning curve than the lower-level APIs such as JDOM, but that's outweighed by the lesser development effortdon't think that would work for the original problem, which seemed to indicate that the xml had an unknown structure.

  • Probem with SAX parser

    Hi to averybody!
    I'm trying to parse a xml file using SAX parser but I found a problem.
    When the method
    public void characters(char[] ch, int start, int length)
    I try to print the content in this way:
    for (int i = start; i <= length; i++)
    System.out.print(ch);
    but nothing is printed except except in 2 cases.
    the file parsed start like this:
    <BatchMaint xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.ncr.com/bosphoenix/WSMaintenance_5.0.xsd">
    <Id>1000950</Id>
    <DateTime>2009-02-11T11:37:09</DateTime>
    <FromPC>TD185008-1J7</FromPC>
    <FromAppl>BatchToPosWS.dll</FromAppl>
    <FromVersion>001.000.000.000</FromVersion>
    the method print only "1000950" and "2009-02-11T11:37:09".
    Has somebody any idea how fix the problem??

    From the API documentation for the characters() method:
    "The Parser will call this method to report each chunk of character data. SAX parsers may return all contiguous character data in a single chunk, or they may split it into several chunks; however, all of the characters in any single event must come from the same external entity so that the Locator provides useful information."

  • How can we get  tag of XML file using SAX

    Hi ,
    I'm parsing one SAX parser , I'have almost done this parsing. i have faced problem for one case, i'e how can we get tag from XML file using SAX parser?
    XML file is
    <DFProperties>
    <AccessType>
    <Get/>
    </AccessType> <Description>
    gdhhd
    </Description>
    <DFFormat>
    <chr/>
    </DFFormat>
    <Scope>
    <Permanent/>
    </Scope>
    <DFTitle>gsgd</DFTitle>
    <DFType>
    <MIME>text/plain</MIME>
    </DFType>
    </DFProperties>
    I want out like GET and Permanent... means this one tag which is present inside of another tag.
    Handler class like
    public void startElement(String namespaceURI, String localName,
                   String qName, Attributes atts) throws SAXException {
    if(_ACCESSTYPE.equals(localName)){
                   accessTypeElement=ACCESSTYPE;
    public void characters(char[] ch, int start, int length)
                   throws SAXException {
    if (_ACCESSTYPE.equals(_accessTypeElement)) {
                   String strValue = new String(ch, start, length);
                   System.out.println("Accestype-----------------------------> " + strValue);
                   //System.out.println(" " + strValue);
    public void endElement(String namespaceURI, String localName, String qName)
                   throws SAXException {
    if (_ACCESSTYPE.equals(localName)) {
                   _accessTypeElement = "";
    . please any body help me

    Hi ,
    I have one problem,Please help me.
    1. How can I'll identify where exactly my Node is ended,means how how can we find corresponding nodename? in partcular place
    <Node> .............starttag1
    <NodeName>Test</NodeName>
    <Node>................starttag2
    <nodeName>test1</NodeName>
    </Node>..................endtag2
    <Node>.....................starttag3
    <NodeName><NodeName>
    <Node> .........................starttag4
    <NodeName>test4</NodeName>
    </Node>.......enddtag4
    </Node>...........end tag3
    </Node>............endtag1
    my code is below
    private final String _NODENAME = "NodeName";
    private final String _NODE = "Node";
    private String _nodeElement = "";
         private String _NodeNameElement = "";
    public void startElement(String namespaceURI, String localName,
                   String qName, Attributes atts) throws SAXException {
    if (_NODENAME.equals(localName)) {
                   NodeNameElement = NODENAME;
    if(_NODE.equals(localName)){
         System.out.println("start");
         if (_NODENAME.equals(localName)) {
                   NodeNameElement = NODENAME;
    public void characters(char[] ch, int start, int length)
                   throws SAXException {
    if (_NODENAME.equals(_NodeNameElement)) {
                   String strValue = new String(ch, start, length);
                   String sttt=strValue;
                   System.out.println("NODENAME: ************* " + strValue);
    if(_NODE.equals(_nodeElement)){
                   if (_NODENAME.equals(_NodeNameElement)) {
                        String strValue = new String(ch, start, length);
                        String sttt=strValue;
                        System.out.println("nodevalue********** " + strValue);
    public void endElement(String namespaceURI, String localName, String qName)
                   throws SAXException {
    if (_NODENAME.equals(localName)) {
                   _NodeNameElement = "";
    if(_NODE.equals(localName)){
                   System.out.println("NODENAME: %%%%%%%%%");
    please help me. How can I figure node ending for particular nodename

  • Parsing XML file with different languages (Xerces)

    How do we code or program to an XML file with different
    languages , say english and spanish. WHen we parse such a document with the default locale , the presence of special characters throws errors .For eg when I use xerces and use
    DOMParser parser = new DOMParser();
    try
    // Parse the XML Document
    parser.parse(xmlFile);
    catch (SAXException se)
    se.printStackTrace();
    org.xml.sax.SAXParseException: An invalid XML character (Unicode: 0xfc) was found in the element content of the document.
    System Error:          void org.apache.xerces.framework.XMLParser.parse(org.xml.sax.InputSource)
    So what locale do we set before we parse ?How to handle this problem

    You need an encoding attribute in the xml declaration. If you don't, the parser assumes UTF-8, which are ASCII characters up to 127 - useful (only) for English.
    So, something like this would allow you to use characters above 127, ISO-8859-1 is the encoding used by standard PCs.
    <?xml version="1.0" encoding="ISO-8859-1"?>
    You can find a (offical) list of encodings at:
    http://www.iana.org/assignments/character-sets
    I'm not sure about mixing various encodings. I think you have to resort external parsed entities, which can have their own encoding, but I think you cannot mix encodings in one XML file.
    Good luck.

Maybe you are looking for

  • Youtube - Does not work in all Browsers

    Greetings, I have an issue were Youtube is not functional in any of my web browsers (Safari, Firefox, and Chrome). I cannot find a fix to this issue anywhere else. All I keep getting is "An error occured, please try again later". I have I have tried

  • ABAP server proxy help required

    Hello, I want to make two simple ABAP server proxy scenarios 1. File to ABAP server proxy (async scenario) 2. File to ABAP server proxy (sync scenario) Pls send me the blogs/docs for the above scenarios. Regards

  • How do you create Client Data Model Definition (cpx) in 10.1.2  struts proj

    I recently upgraded to 10.1.2 and am starting a new project with a BC4J model project and a struts view project, for the life of me I can't see how to create a New Client Data Model Definition in 10g! Searching through the help I couldn't find a clea

  • Going crazy trying to connect iPhone to computer/iTunes

    I had iTunes installed on my computer, and everything was fine. Didn't have a single problem with it. Then, when I got my new motherboard and processor yesterday, I reinstalled Windows 7, something I do any time I get a new motherboard. So I install

  • Cant get music off of it

    Ok first of all I had no idea where to post this. I have a Ipod nano(not the new one). I need to reset it but beore I do I need to get some of the music off of it. When I connect it to itunes and try to drag the music to the library it will not go...