How to add/insert a xml node into text

5.4k views Asked by At

I am generating a text document in the open document format (odt) which is based on XML. But I have a problem when adding a tabulator in a text passage. When I create it in the Open Office application and save the document the passage has the internal XML representation as:

<text:p text:style-name="P5">Prepared by: <text:tab/>Tim Test</text:p>

When generating it automatically I come to this part in my source code:

   Node, Node1: IXMLNode;
   ...
   Node := Node1.AddChild('text:p');
   Node.Attributes['text:style-name'] := 'P5';
   Node.Text := 'Prepared by: Tim Test';

But I can't find any method to add the node into the text before "Tim", or at least not with the internal Delphi XML library.

Is there a way to achieve it or is there any other Delphi XML library which can do that?

1

There are 1 answers

2
Remy Lebeau On BEST ANSWER

Keep in mind that XML is a hierarchy of nodes, including text snippets. The XML you showed looks like this in a tree:

[element] 'text:p'
  │
  ├─[attributes]
  │   │
  │   └─[attribute] 'text:style-name'
  │       │
  │       └─[text] 'PS'
  │
  └─[children]
      |
      ├─[text] 'Prepared by: '
      │
      ├─[element] 'text:tab'
      │ 
      └─[text] 'Tim Test'

That should help you visualize how you have to add nodes to your document to get the desired output, eg:

Node, Node1, Node2: IXMLNode;
...
Node := Node1.AddChild('text:p');
Node.Attributes['text:style-name'] := 'P5';

Node2 := Node.OwnerDocument.CreateNode('Prepared by: ', ntText);
Node.ChildNodes.Add(Node2);

Node2 := Node.OwnerDocument.CreateElement('text:tab', '');
Node.ChildNodes.Add(Node2);

Node2 := Node.OwnerDocument.CreateNode('Tim Test', ntText);
Node.ChildNodes.Add(Node2);