I'm creating an XML file in Delphi 7. I want to remove the declaration of the parent node from the code.
This is my code:
var
XML : IXMLDOCUMENT;
RootNode, CurNode : IXMLNODE;
begin
XML := NewXMLDocument;
XML.Encoding := 'utf-8';
XML.Options := [doNodeAutoIndent]; // looks better in Editor ;)
RootNode := XML.AddChild('p:test');
RootNode.Attributes['xmlns:ds'] := 'Attributes1';
RootNode.Attributes['xmlns:p'] := 'Attributes2';
RootNode.Attributes['versione'] := 'FPR12';
CurNode := RootNode.AddChild('HeadNode');
CurNode := CurNode.AddChild('SubNode');
CurNode.Text := 'Test';
CurNode := CurNode.ParentNode;
CurNode := CurNode.AddChild('Codice');
CurNode.Text := '01234567890';
CurNode := CurNode.ParentNode;
CurNode := CurNode.ParentNode;
s := 'C:\Users\web\Desktop\file.xml';
XMl.SaveToFile(s);
end;
This is my Result:
<?xml version="1.0" encoding="utf-8"?>
<p:test xmlns:ds="Attributes1" xmlns:p="Attributes2" versione="FPR12">
<p:HeadNode>
<p:SubNode>Test</p:SubNode>
<p:Codice>01234567890</p:Codice>
</p:HeadNode>
</p:test>
This is what I expected to have (note the missing "p:" on HeadNode and its nested nodes):
<?xml version="1.0" encoding="utf-8"?>
<p:test xmlns:ds="Attributes1" xmlns:p="Attributes2" versione="FPR12">
<HeadNode>
<SubNode>Test</SubNode>
<Codice>01234567890</Codice>
</HeadNode>
</p:test>
How can I get this?
This is normal behavior, any node that is created under a parent node will carry the namespace of the parent node. Since you want that Node HeadNode
does not carry a namespace, you must assign an empty namespace when you create that node. If you look at function TXMLNode.AddChild
, you will see that there is an overload function that accepts a second parameter that represents the NameSpaceUri
for that node.
So to fix your XML, all you have to do is change line CurNode := RootNode.AddChild('HeadNode');
into CurNode := RootNode.AddChild('HeadNode', '');
Compilable example:
program SO58008911;
{$APPTYPE CONSOLE}
{$R *.res}
uses
ActiveX,
XMLIntf,
XMLDoc,
System.SysUtils;
procedure TestXML;
var
XML : IXMLDOCUMENT;
RootNode, CurNode : IXMLNODE;
begin
XML := NewXMLDocument;
XML.Encoding := 'utf-8';
XML.Options := [doNodeAutoIndent]; // looks better in Editor ;)
RootNode := XML.AddChild('p:test');
RootNode.Attributes['xmlns:ds'] := 'Attributes1';
RootNode.Attributes['xmlns:p'] := 'Attributes2';
RootNode.Attributes['versione'] := 'FPR12';
CurNode := RootNode.AddChild('HeadNode', '');
CurNode := CurNode.AddChild('SubNode');
CurNode.Text := 'Test';
CurNode := CurNode.ParentNode;
CurNode := CurNode.AddChild('Codice');
CurNode.Text := '01234567890';
Writeln(XML.XML.Text);
end;
begin
try
CoInitialize(nil);
try
TestXML;
finally
CoUninitialize;
end;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
Readln;
end.
Output:
<?xml version="1.0"?>
<p:test xmlns:ds="Attributes1" xmlns:p="Attributes2" versione="FPR12">
<HeadNode>
<SubNode>Test</SubNode>
<Codice>01234567890</Codice>
</HeadNode>
</p:test>