We help IT Professionals succeed at work.

How can I delete a line from a XML?

hidrau
hidrau asked
on
Hello Guys

I have a XML that has this line <?xml version="1.0"?>

I need a function that can open the file, delete this line and save the file.

I am attaching a xml with this line

thanks
PO-20483.xml
Comment
Watch Question

You just read it as a text file and drop line 1.  There are many bits of code to do this already

http://www.google.com/search?q=delphi+edit+text+file

My comment was not how to fix it - but a question.... why ?
If you remove this line then you are making in into an invalid XML file.
Why not just ignore it in the app you are reading it with later instead of editing all the files.
Mike McCrackenSenior Consultant
CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2013

Commented:
Agree.  WIthout that line most applications won't recognize it or be able to use it as an XML file.

mlmcc

Author

Commented:
that line is not necessary in the file.

if I delete it the XML file works fine
Mike McCrackenSenior Consultant
CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2013

Commented:
I don't have a way to write Pascal code and test it but a basic method would be

Open the file for input - INPUT
Open a file for output - OUTPUT
Read a line from INPUT  -  Skip first line
WHile NOT EOF(INPUT)
   ReadLN INPUT
    WriteLN OUTPUT
Wend

Close INPUT
Close OUTPUT

mlmcc

Commented:
Load file into a StringList, search for line, delete if found and save back to file...

procedure DeleteXMLVersionLine(fname:string);
var
  sl:TstringList;
  idx:integer;
begin
  if FileExists(fname) then begin
    sl:=TStringList.Create;
    sl.LoadFromFile(fname);
    idx:=sl.IndexOf('<?xml version="1.0"?>');
    if idx > -1 then begin
      sl.Delete(idx);
      sl.SaveToFile(fname);
    end;

    sl.Free;
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  DeleteXMLVersionLine('c:\swap\test.xml');
end;

Open in new window

Author

Commented:
Thommy,

I tested with a xml here and your function didn't find this <?xml version="1.0"?>.

:(
Senior Consultant
CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2013
Commented:
May have to look for just

xml version="1.0"

or may have to escape the ? since they may be being interpreted as wildcards

'<\?xml version="1.0"\?>'

or even

'<' & chr(asc('?')) & 'xml version="1.0"' & chr(asc('?')) '>'

mlmcc

Commented:
Can you post your XML file for testing...

Author

Commented:
thanks very much

Explore More ContentExplore courses, solutions, and other research materials related to this topic.