Download Reference Manual
The Developer's Library for D
About Wiki Forums Source Search Contact

Reading XML files

Moderators: larsivi kris

Posted: 11/02/08 03:45:17

Hello

How to read an XML document like this with Tango?

<?xml version="1.0"?>
<settings>
    <key name="title" value="Hello World"/>
    <key name="color" value="blue"/>
</settings>

To load the xml file, iterate for each child node in the "settings" node, and get the "name" and "value" attributes

Thanks

Author Message

Posted: 11/02/08 06:05:54 -- Modified: 11/02/08 06:24:12 by
kris -- Modified 2 Times

Assuming you've loaded the xml into a char[] called myXml, the documentation in tango.text.xml.Document indicates one should try something like this:

import tango.text.xml.Document;

auto doc = new Document!(char);
doc.parse (myXml);

foreach (pair; doc.query["settings"]["key"])
        {
        auto name = pair.getAttribute("name").value;
        auto value = pair.getAttribute("value").value;
        }

Be aware that getAttribute() will return null if the named attribute is not present. One way to load xml from a file would be:

import tango.io.File;

auto myXml = cast(char[]) File("myFile.xml").read;

Hope that helps?

Posted: 11/02/08 11:28:21

Yes, it's just what I needed

I dont understand at all the documentation... sorry... my english is very bad (I think that it would be easier to learn with a single example showing how to load, read, and get attributes, as you've written)

Thanks, for this great library and response!

Posted: 11/02/08 17:37:00

you're welcome. I agree we need more examples, and there's a wiki available for people to add their own :)