Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use NativeXml to deal with XML in Delphi

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

It is believed that many inexperienced people have no idea about how to use NativeXml to deal with XML in Delphi. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

Example of using NativeXml

3.1. Loading, storage, and export of example A:XML

This example shows how to load an XML document and then export it to an TMemo realm in a readable format.

Drag and drop a TEdit (Edit1), TButton (Button1) and a TMemo to your form, and then connect to the OnClick event code of the button below. Fill in the file name to Edit1, then click the button, and you will see the contents of the XML file listed in the memo control.

Procedure TForm1.Button1Click (Sender: TObject)

Var

ADoc: TNativeXml

Begin

Memo1.Lines.Clear

ADoc: = TNativeXml.Create

Try

ADoc.LoadFromFile (Edit1.Text)

ADoc.XmlFormat: = xfReadable

Memo1.Lines.Text: = ADoc.WriteToString

Finally

ADoc.Free

End

End

Note that ADoc.XmlFormat:= xfReadable will ensure that the file is listed in an easy-to-read form (with carriage returns and indentation).

3.2. Example B: connect to a node

This example shows how to access individual nodes in a XML file. A node can start from a normal XML tag, comment, CDATA structure, and so on. This example shows how to use a simple double loop to list the nodes in the first two layers.

Add Tedit, TButton, and TMemo to the form, and then connect the following event code to the button's OnClick. Then fill in the file name in Edit1, press the button, and the nodes of the first two layers will be listed in the memo control.

Procedure TForm1.Button2Click (Sender: TObject)

Var

I, j: integer

ADoc: TNativeXml

Begin

Memo1.Lines.Clear

ADoc: = TNativeXml.Create

Try

ADoc.LoadFromFile (Edit1.Text)

If assigned (ADoc.Root) then with ADoc.Root do

For I: = 0 to NodeCount-1 do begin

Memo1.Lines.Add (Nodes [I] .Name)

For j: = 0 to Nodes [I] .NodeCount-1 do

Memo1.Lines.Add ('+ Nodes [I]. Nodes [j] .Name)

End

Finally

ADoc.Free

End

End

3.3. Example C: event-driven processing

This example shows that NativeXml can read files sequentially in a SAX-like manner, generating events whenever a node is initialized and loaded.

Add a TButton (Button3) and a TMemo (Memo1) to your form, and then include NativeXml in the uses. Next, type the following TButton.OnClick event handler code.

Procedure TForm1.Button3Click (Sender: TObject)

Var

ADoc: TNativeXml

Begin

Memo1.Lines.Clear

ADoc: = TNativeXml.Create

Try

ADoc.OnNodeNew: = DoNodeNew

ADoc.OnNodeLoaded: = DoNodeLoaded

ADoc.LoadFromFile (Edit1.Text)

Finally

ADoc.Free

End

End

Type the following program code in the new TForm1:

Function TForm1.Indent (ACount: integer): string

Begin

While ACount > 0 do begin

Result: = Result +''

Dec (ACount)

End

End

Procedure TForm1.DoNodeNew (Sender: TObject; Node: TXmlNode)

Begin

Memo1.Lines.Add (Format ('New:% sName=%s', [Indent (Node.TreeDepth), Node.Name]))

End

Procedure TForm1.DoNodeLoaded (Sender: TObject; Node: TXmlNode)

Begin

Memo1.Lines.Add (Format ('Loaded:% sName=%s, Value=%s', [In dent (Node.TreeDepth), Node.Name, Node.ValueAsString]))

End

When a node is found, the OnNodeNew event is triggered, and whenever a node is fully loaded, the OnNodeLoaded event is triggered.

If you do not want to keep a complete copy of the XML file in memory, for example, for a large XML file, you can simply delete the node and free up its memory. In this case, add the following code to the OnNodeLoaded event:

Procedure TForm1.DoNodeLoaded (Sender: TObject; Node: TXmlNode)

Begin

Memo1.Lines.Add (Format ('Loaded: Name=%s, Value=%s', [Node.Name, Node.ValueAsString]))

If Node.TreeDepth > 0 then begin

Memo1.Lines.Add (Format ('Deleted: Name=%s', [Node.Name]))

Node.Delete

End

End

3.4. Example D: create a simple XML file

This example demonstrates how to create a simple XML file with a node under the root node with an attribute and a child node. We will try to create this XML file:

John Doe

Here is the code for a procedure that creates this file and saves it to a file named "C:\ test.xml" in an easy-to-read format:

Procedure CreateXML

Var

ADoc: TNativeXml

Begin

/ / Create new document with a rootnode called "Root"

ADoc: = TNativeXml.CreateName ('Root')

Try

/ / Add a subnode with name "Customer"

With ADoc.Root.NodeNew ('Customer') do begin

/ / Add an attribute to this subnode

WriteAttributeInteger ('ID', 123456)

/ / Add subsubnode

WriteString ('Name',' John Doe')

End

/ / Save the XML in readable format (so with indents)

ADoc.XmlFormat: = xfReadable

/ / Save results to a file

ADoc.SaveToFile ('c:\ test.xml')

Finally

ADoc.Free

End

End

3.5. Example E: files encoded in UTF8 and Unicode (widestring supported)

This example shows how to create and load a XML file that supports widestrings.

3.5.1.NativeXml internal coding

NativeXml can work in two "modes": either all internal strings are plain ANSI strings or all internal strings are UTF8-encoded strings. The string type does not change (it is still "string"). Although Delphi7 has a special type of "Utf8String", it is not used to maintain the compatibility of lower versions of Delphi.

To make sure your XML document can use widestrings, create it, and then directly set the property "Utf8Encoded" to True, as shown below:

Procedure CreateXML

Var

ADoc: TNativeXml

Begin

ADoc: = TNativeXml.CreateName ('Root')

Try

/ / Make sure to be able to handle widestrings

ADoc.Utf8Encoded: = True

/ /.. add all your creation code here

Finally

ADoc.Free

End

End

3.5.2.NativeXml external coding

When saving your document, select the appropriate encoding for the external file or stream (SaveToStream also needs to save the correct encoding). Set the property "ExternalEncoding" to any of the values:

Se8bit: this returns a pure ASCII file with all Unicode/widestring character values higher than $FF. This is the default value.

SeUTF16LE: this returns the byte order tag $FF FE of a Unicode file. This should be the default for an Unicode file.

SeUTF16BE: this returns the byte order mark $FE FF of the large byte (big-endian) Unicode file.

SeUTF8: this returns the byte order tag $FF BB BF of a UTF-8-encoded file. UTF-8 is a better way to store when most of the characters are Western or Latin. However, it can provide more space for multiple languages such as Chinese or Japanese.

Here is an example of how to set an external code:

Procedure CreateXML

Var

ADoc: TNativeXml

Begin

ADoc: = TNativeXml.CreateName ('Root')

Try

/ / Make sure to be able to handle widestrings

ADoc.Utf8Encoded: = True

/ /.. add all your creation code here

/ / Save to unicode

ADoc.ExternalEncoding: = seUTF16LE

ADoc.EncodingString: = 'UTF-16'

ADoc.SaveToFile ('c:\ temp\ test.xml')

Finally

ADoc.Free

End

End

3.5.3. Add widestrings

It is easy to add widestrings to the document. The value of each node can be set to widestring, the ValueAsWidestring of the attribute can be used, and the widestrings can be added in general using the FromWidestring function.

The following example code adds a new node to the root, and then sets the node name (Name) to Aname and the node value (value) to AValue:

Procedure AddNode (ADoc: TXmlDocument; AName, AValue: widestring)

Begin

With ADoc.Root do

With NodeNew (FromWidestring (AName)) do

ValueAsWidestring: = AValue

End

3.5.4. Load extended characters of the XML file

When reading a XML file that contains extended characters, it is important to set Utf8Encoded to True before introduction, like this:

Function CreateXMLAndLoadFromFile (AFilename: string): TNativeXml

Begin

Result: = TNativeXml.Create

Result.Utf8Encoded: = True

Result.LoadFromFile (AFilename)

End

When read from a stream (for example, from a TCP connection), the stream does not always contain byte order marks (BOM). However, if the stream is Unicode,NativeXml, it will be recognized, so it won't help. For example:

Function CreateXMLAndLoadFromStream (S: TStream): TNativeXml

Begin

Result: = TNativeXml.Create

Result.Utf8Encoded: = True

Result.LoadFromStream (S)

End

If you know that your stream has a certain encoding, you can force NativeXml to use this encoding, for example:

Function CreateXMLAndLoadFromUTF8Stream (S: TStream): TNativeXml

Begin

Result: = TNativeXml.Create

Result.Utf8Encoded: = True

/ / The stream is encoded using UTF8

Result.ExternalEncoding: = seUTF8

Result.LoadFromStream (S)

End

After reading the above, have you mastered how to use NativeXml to deal with XML in Delphi? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report