Ildar ha scritto:
> hi all,
> 
> I'm new here and might miss the page that describes what I need. Please, send 
> me the link to the page this case.
> 
> 
> I'm playing with the following XML.
> 
> <?xml version="1.0" encoding="utf-8"?>
> <root>
>   <level1>
>     <level2-1>hello</level2-1>
>   </level1>
> </root>
> 
> I need to get the content of /root/level1/level2-1.
> My code is as follows:
> 
> wxXml2Document doc;
> wxString err;
> 
> doc.Load(wxT("****.xml"), &err);
> 
> if (doc.IsOk())
> {
>     wxXml2Node node = doc.GetRoot();
>     wxString s = node.Find(wxT("level2-1")).GetName();
>     wxString s1 = node.Find(wxT("level2-1")).GetContent();
>     wxString s2 = node.Find(wxT("level2-1")).GetFirstChild().GetContent();
> }
> 
> the results are:
> 
> s == "level2-1" // the same as expected
> s1 == "" // I expected to get "hello"
> s2 == "hello" // ?
yes, sure. no bugs.
This is really a FAQ and I should add it somewhere.

The results you get are because your XML tree is parsed as:

wxXML_ELEMENT_NODE with name "root" and content=""
|- wxXML_ELEMENT_NODE with name "level1" and content=""
    |- wxXML_ELEMENT_NODE with name "level2-1" and content=""
       |- wxXML_TEXT_NODE with name "" and content="hello"

Thus, if the node is an element node, you shouldn't look at its contents 
but rather at its children.
If the node is a text node, the name is empty (or maybe fixed to "text", 
I don't remember) and you should just look at his contents.

I've added in CVS the GetNodeContent() function which simplifies the 
process (see below).


> The way I'm accessing the value is quite weird and doesn't seem to be safe...
 >
 > Is there an easier way?

wxXml2Node child = doc.GetRoot();
while (child != wxXml2EmptyNode) {

     if (child.GetName() == wxT("level1")) {

         // process text enclosed by <level1>
         wxString content = child->GetNodeContent();

     } else if (child->GetName() == wxT("tag2")) {

         // process tag2 ...
     }
     else
     {
         // unknown tag?
     }

     child = child.GetNext();
}

this pattern allows you to scan each node of the XML and e.g. catch 
structural errors (e.g. you can check for unknown tags).


Francesco


-------------------------------------------------------------------------
Take Surveys. Earn Cash. Influence the Future of IT
Join SourceForge.net's Techsay panel and you'll get the chance to share your
opinions on IT & business topics through brief surveys -- and earn cash
http://www.techsay.com/default.php?page=join.php&p=sourceforge&CID=DEVDEV
_______________________________________________
wxCode-users mailing list
wxCode-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/wxcode-users

Reply via email to