Search code examples
delphidelphi-7omnixml

Adding line break in NodeAttributes in OmniXML


I have an XML where I have several attributes for one node:

var
  row  : IXMLNode;
  rowattr : IXMLAttr;
  xml  : IXMLDocument;
begin
  xml := ConstructXMLDocument('xml');
  SetNodeAttr(xml.DocumentElement, 'version', '1.0');
  SetNodeAttr(xml.DocumentElement, 'encoding', 'UTF-8');
  row := AppendNode(xml, 'Links');
  rowattr:=xml.CreateAttribute('Link1');
  rowattr.Value:='http:\\wwww.somelink1.com';
  row.Attributes.SetNamedItem(rowattr);
  rowattr:=xml.CreateAttribute('Link2');
  rowattr.Value:='http:\\wwww.somelink2.com';
  row.Attributes.SetNamedItem(rowattr);
  rowattr:=xml.CreateAttribute('Link3');
  rowattr.Value:='http:\\wwww.somelink3.com';
  row.Attributes.SetNamedItem(rowattr);
  XMLSaveToFile(xml, 'C:\Test1.xml', ofIndent);
end;

I wish to have every link on a separate line like this:

<xml version="1.0" encoding="UTF-8">
  <Links
  link1="http://www.somelink1.com" 
  link2="http://www.somelink2.com"
  link3="http://www.somelink3.com" 
  />
</xml>

Solution

  • OmniXML does not offer such fine grained control of output formatting. You could perhaps look to find an external XML pretty printer that will do what you need. Or you could even write your own XML library.

    Before you go any further though I would like to make the point that XML was never intended to be read by humans. Its design makes no effort to be readable, and if you continue trying to make your XML as readable as possible, then you will be swimming against the tide. If you want a human readable structured file format then you might look instead at YAML which was designed with that in mind.

    Another avenue to consider is the structure of the XML. Using node attributes to specify an array of values is a poor decision. Attributes are intended to be used with name/value mapping pairs. If you want to specify an array of values then you might do so like this:

    <links>
        <item>http://www.somelink1.com</item>
        <item>http://www.somelink2.com</item>
        <item>http://www.somelink3.com</item>
    </links>
    

    This is clearer than your XML and much easier to parse. Try writing code to parse your attributes and you will see what I mean.

    Now, just to illustrate my point above, in YAML this would be:

    Links:
        - http://www.somelink1.com
        - http://www.somelink2.com
        - http://www.somelink3.com
    

    Of course, all this is moot if somebody other than you is defining the format of the XML.