Hallo Steffen,
es gibt viele Wege, wie du einen Node umbenennen kannst. Ich zeige dir, wie du diese Aufgabe vom
MSXML Parser erledigen lassen kannst:
Delphi-Quellcode:
// uses MSXML2;
procedure RenameElements(doc: IXMLDOMDocument;
const sXPath, sNewTagName:
string);
const
TransformCode
= '
<?xml version="1.0"?>'
+ '
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">'
+ '
<xsl:template match="%s">'
+ '
<xsl:element name="%s">'
+ '
<xsl:apply-templates select="@* | node()"/>'
+ '
</xsl:element>'
+ '
</xsl:template>'
+ '
<xsl:template match="/ | @* | node()">'
+ '
<xsl:copy>'
+ '
<xsl:apply-templates select="@* | node()"/>'
+ '
</xsl:copy>'
+ '
</xsl:template>'
+ '
</xsl:stylesheet>'
;
var
xsl: IXMLDOMDocument;
begin
xsl := CODOMDocument.Create;
xsl.async := false;
xsl.loadXML(Format(TransformCode, [sXPath, sNewTagName]));
doc.loadXML(doc.transformNode(xsl));
end;
So kannst du den Code testen:
Delphi-Quellcode:
procedure TDemoForm.RenameButtonClick(Sender: TObject);
const
SampleXML
= '<root>'
+ ' <alt id="1"><subelement id="101"/></alt>'
+ ' <test id="10"><subelement id="1001"/></test>'
+ ' <alt id="2"><subelement id="201"/></alt>'
+ ' <test id="20">'
+ ' <alt id="3">DEMO</alt>'
+ ' <alt id="4"><subelement id="401"/></alt>'
+ ' </test>'
+ '</root>'
;
var
doc: IXMLDOMDocument;
xpath: string;
begin
doc := CODOMDocument.Create;
doc.async := false;
// rename second top level occurrence
doc.loadXML(SampleXML);
xpath := '/*/alt[2]';
RenameElements(doc, xpath, 'neu');
ShowMessage(xpath + #13#13 + doc.xml);
// rename all second level occurrences
doc.loadXML(SampleXML);
xpath := '/*/*/alt';
RenameElements(doc, xpath, 'neu');
ShowMessage(xpath + #13#13 + doc.xml);
// rename all occurrences
doc.loadXML(SampleXML);
xpath := '//alt';
RenameElements(doc, xpath, 'neu');
ShowMessage(xpath + #13#13 + doc.xml);
end;
Grüße vom marabu