Why is this loop only running once? - c++

Why is this loop only running once?
noteDatabaseItem just takes a node and fills in the data. the xml has 3 notes in it.
XML:
<?xml version="1.0" encoding="utf-8"?>
<noteCollection>
<note name="Test Note 1">This is test note 1 content!</note>
<note name="Test Note 2">This is test note 2 content!</note>
<note name="Test Note 3">This is test note 3 content!</note>
</noteCollection>
C++:
std::vector<notekeeper::noteDatabaseItem> noteList;
TiXmlElement* noteCollection = xmlDoc->FirstChildElement("noteCollection");
TiXmlElement* node = noteCollection->FirstChildElement("note");
int itemCount = 0;
while (node != NULL) {
itemCount++;
noteList.resize(itemCount);
noteList.push_back(noteDatabaseItem(node));
node = noteCollection->NextSiblingElement("note");
}

Shouldn't it be node = node->NextSiblingElement("note")?
noteCollection has only children, not siblings, right?

You're getting the wrong element in your loop. Try this:
while (node != NULL) {
itemCount++;
noteList.push_back(noteDatabaseItem(node));
node = node->NextSiblingElement("note");
}
The next sibling of the current node is the one you want. You were trying to get the next sibling of the parent node.

node = noteCollection->NextSiblingElement("note");
is meant to be
node = node->NextSiblingElement("note");
Stupid mistake. Sibling not Child.

Related

parsing comment in tinyXML2

I have problem with parsing XML comment. How can i properly access to comment?
Or is even possible to read comment with tinyXML2?
<xml>
<foo> Text <!-- COMMENT --> <foo2/></foo>
</xml>
I created
XMLElement *root = xmlDoc->FirstChildElement("foo");
XMLElement *child = root->FirstChildElement();
From child element i get foo2 element, What is propper way to read comment element from file.
Thanks
You can use XMLNode::FirstChild() and XMLNode::NextSibling() to loop through all child nodes. Use dynamic_cast to test if node is a comment.
if( const XMLElement *root = xmlDoc->FirstChildElement("foo") )
{
for( const XMLNode* node = root->FirstChild(); node; node = node->NextSibling() )
{
if( auto comment = dynamic_cast<const XMLComment*>( node ) )
{
const char* commentText = comment->Value();
}
}
}
I've made this up just from reading the documentation, so there might be mistakes in the code.
I just created a function on my project that navigates the entire document recursively and get rid of comments. You can use that to see how you can pick up any comment on the document... followed the example of the fellow above..
Code bellow:
// Recursively navigates the XML and get rid of comments.
void StripXMLInfo(tinyxml2::XMLNode* node)
{
// All XML nodes may have children and siblings. So for each valid node, first we
// iterate on it's (possible) children, and then we proceed to clear the node itself and jump
// to the next sibling
while (node)
{
if (node->FirstChild() != NULL)
StripXMLInfo(node->FirstChild());
//Check to see if current node is a comment
auto comment = dynamic_cast<tinyxml2::XMLComment*>(node);
if (comment)
{
// If it is, we ask the parent to delete this, but first move pointer to next member so we don't get lost in a NULL reference
node = node->NextSibling();
comment->Parent()->DeleteChild(comment);
}
else
node = node->NextSibling();
}
}

Deleting specific node of XML file

Below I have a sample of my XML file, I want to delete a specific node in each header. How do i do it. for example in header<HEADER> i want to delete the node <ADDRESS>, not just its attribute but the whole node. in <HEADER1> I need to delete the attribute <UMG_VAR Name="ABC" Value=1></UMG_var>, here Name attribute is unique.
<MAIN>
<HEADER>
<TITLE>ppc_ph_pios</TITLE>
<AUTOR>DNL</AUTOR>
<AGE>age</AGE>
<SEX>Male</SEX>
<PLACE>Earth</PLACE>
<ADDRESS>abc</ADDRESS>
</HEADER>
<HEADER1>
<UMG_VAR Name="RED" Value="3"></UMG_VAR>
<UMG_VAR Name="ABC2" Value="2"></UMG_VAR>
<UMG_VAR Name="ABC" Value="1"></UMG_VAR>
</HEADER2>
</MAIN>
QDomDocument doc;
doc.setContent(oldXml);
QDomNodeList nodes = doc.elementsByTagName("element");
for (int i = 0; i < nodes.count(); ++i)
{
QDomNode node = nodes.at(i);
QDomElement child = node.firstChildElement("child");
if (!child.isNull() && child.attribute("id") == "0")
{
node.removeChild(child);
}
}
QString newXml = doc.toString();

TinyXML2 - insert element in middle of XML

I'm looking to add new elements with data to the middle of my XML structure. How can I append them where I need them?
Current code:
XMLElement *node = doc.NewElement("timeStamp");
XMLText *text = doc.NewText("new time data");
node->LinkEndChild(text);
doc.FirstChildElement("homeML")->FirstChildElement("mobileDevice")->FirstChildElement("event")->LinkEndChild(node);
doc.SaveFile("homeML.xml");
And an example part of my XML structure:
<mobileDevice>
<mDeviceID/>
<deviceDescription/>
<units/>
<devicePlacement/>
<quantisationResolution/>
<realTimeInformation>
<runID/>
<sampleRate/>
<startTimeStamp/>
<endTimeStamp/>
<data/>
</realTimeInformation>
<event>
<mEventID/>
<timeStamp/>
<data/>
<support/>
</event>
</mobileDevice>
I'm looking to add it addtional timeStamp tags under mobileDevice->event between mEventID and data, at the moment they are being appended after the support tag how can I get them to be entered in the correct place?
Current placement when ran:
<mobileDevice>
<mDeviceID/>
<deviceDescription/>
<units/>
<devicePlacement/>
<quantisationResolution/>
<realTimeInformation>
<runID/>
<sampleRate/>
<startTimeStamp/>
<endTimeStamp/>
<data/>
</realTimeInformation>
<event>
<mEventID/>
<timeStamp/>
<data/>
<support/>
<timeStamp>new time data</timeStamp>
</event>
</mobileDevice>
You want to use InsertAfterChild() to do this. Here's an example which should do what you want (assuming that "mobileDevice" is your document's root element):
// Get the 'root' node
XMLElement * pRoot = doc.FirstChildElement("mobileDevice");
// Get the 'event' node
XMLElement * pEvent = pRoot->FirstChildElement("event");
// This is to store the element after which we will insert the new 'timeStamp'
XMLElement * pPrecedent = nullptr;
// Get the _first_ location immediately before where
// a 'timeStamp' element should be placed
XMLElement * pIter = pEvent->FirstChildElement("mEventID");
// Loop through children of 'event' & find the last 'timeStamp' element
while (pIter != nullptr)
{
// Store pIter as the best known location for the new 'timeStamp'
pPrecedent = pIter;
// Attempt to find the next 'timeStamp' element
pIter = pIter->NextSiblingElement("timeStamp");
}
if (pPrecedent != nullptr)
{
// Build your new 'timeStamp' element,
XMLElement * pNewTimeStamp = xmlDoc.NewElement("timeStamp");
pNewTimeStamp->SetText("Your data here");
// ..and insert it to the event element like this:
pEvent->InsertAfterChild(pPrecedent, pNewTimeStamp);
}
This is an interesting and probably common use case. I wrote a TinyXML2 tutorial a couple of months ago, so I'll add this to it.

Getting the value from a leaf node

I have the following XML subtree:
<xdm:Device xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bsi="http://www.hp.com/schemas/imaging/con/bsi/2003/08/21" xmlns:dd="http://www.hp.com/schemas/imaging/con/dictionaries/1.0/" xmlns:pwg="http://www.hp.com/schemas/imaging/con/pwg/sm/1.0/" xmlns:xdm="http://www.hp.com/schemas/imaging/con/xdm/1.1/" xmlns:alerts="http://www.hp.com/schemas/imaging/con/alerts/2006/01/13" xmlns:count="http://www.hp.com/schemas/imaging/con/counter/2006/01/13" xmlns:job="http://www.hp.com/schemas/imaging/con/job/2006/01/13" xmlns:media="http://www.hp.com/schemas/imaging/con/media/2006/01/13" xmlns:icd="http://www.hp.com/schemas/imaging/icd/2006/08/27" language="en-US">
<xdm:Information>
<dd:ModificationNumber>
12
</dd:ModificationNumber>
</xdm:Information>
</xdm:Device>
And I want to get the value of the dd:ModificationNumber. For that, I use the following XPath:
/xdm:Device/xdm:Information/dd:ModificationNumber
And this code:
TiXmlDocument xmlDoc;
xmlDoc.Parse(xmlSubtree, 0, TIXML_ENCODING_UTF8);
TiXmlElement* xmlElement = xmlDoc.FirstChildElement();
xpath_processor xpathProcessor(xmlElement, xPath);
expression_result expressionResult = xpathProcessor.er_compute_xpath();
int modificationNumber = expressionResult.i_get_int();
However, the resultant expression refers to the root node of the tree, and not to an int as I expected. And the modificationNumber is zero. Any ideas?

Xpath How remove child node by attribute c++ libxml2

How do I remove a child with a specific attribute? I´m using c++/libxml2. My attempt so far (in the example I want to remove child node with id="2"):
Given XML:
<p>
<parent> <--- current context
<child id="1" />
<child id="2" />
<child id="3" />
</parent>
</p>
xmlNodePtr p = (parent node)// Parent node, in my example "current context"
xmlChar* attribute = (xmlChar*)"id";
xmlChar* attribute_value = (xmlChar*)"2";
xmlChar* xml_str;
for(p=p->children; p!=NULL; p=p->next){
xml_str = xmlGetProp(p, attribute);
if(xml_str == attribute_value){
// Remove this node
}
}
xmlFree(xml_str);
Call xmlUnlinkNode to remove a node. Call xmlFreeNode to free it afterward, if you want:
for (p = p->children; p; ) {
// Use xmlStrEqual instead of operator== to avoid comparing literal addresses
if (xmlStrEqual(xml_str, attribute_value)) {
xmlNodePtr node = p;
p = p->next;
xmlUnlinkNode(node);
xmlFreeNode(node);
} else {
p = p->next;
}
}
Haven't used this library in a while, but check out this method. Note that per the description, you need to call xmlUnlinkNode first.