Create a new node and its child nodes from a string - libxml2

I've tried functions xmlNewDocNode and xmlNewDocRawNode, but they both XML-escape the content string we pass to them as a argument. Therefore, it's obviously both of them can only create a single node instead of a subtree. Is there a function that allows us to create a subtree? For instance, if we pass a string <foo><bar>baz</bar></foo> to the function, it will create a subtree:
foo: xmlNode
`- bar: xmlNode
`- baz: plaintext
instead of
foo: xmlNode
`- <bar>baz</bar>: plaintext
Re-edit:
It's doable to parse the text into a temporary document node, and then find the node we want and detach it from the document. This way of creating new node from text seems kind of overkill. I'm wondering is there a libxml2 function that can do it for us.

There is xmlParseBalancedChunkMemory. It's behaviour is slightly more general in that it can parse a series of nodes. But that's easily checked for, as in the following C example:
#include <stdio.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
int
main(int argc, char **argv)
{
xmlDoc *doc = NULL;
xmlNodePtr nodes = NULL;
xmlChar *string = "<foo><bar>baz</bar></foo><blah/>";
int stat = xmlParseBalancedChunkMemory(NULL, NULL, NULL, 0, string, &nodes );
printf("stat: %d\n", stat);
if (stat == 0) {
printf("first: %s\n", nodes->name);
printf("first-child: %s\n", nodes->children->name);
printf("next: %s\n", nodes->next->name);
}
if (nodes != NULL) xmlFreeNodeList(nodes);
}
Output:
stat: 0
first: foo
first-child: bar
next: blah

Related

QtConcurrent mapped with index

I wondered if there is an option to also hand over the current processed index with QtConcurrent::mapped(someVector, &someFunction)) (also filter, filtered, map,...)
What I want: I want to do something with the elements in someVector based on the current index in it. but since the function someFunction is only taking the type T which is also used for the QVector<T> vector.
What I did: Because I needed this, I created a QVector<std::pair<int, T>> and manually created the index for the elements.
Since this requires more space and is not a nice solution, I thought maybe there could be another solution.
Docs: https://doc.qt.io/qt-5/qtconcurrent-index.html
If your input is a QVector, you can make use of the fact that QVector stores all the elements contiguously. This means that given a reference to an element e in a QVector v, then the index of e can be obtained by:
std::ptrdiff_t idx = &e - &v.at(0);
Below is a complete example using QtConcurrent::mapped:
#include <iterator>
#include <numeric>
#include <type_traits>
#include <utility>
#include <QtCore>
#include <QtConcurrent>
// lambda functions are not directly usable in QtConcurrent::mapped, the
// following is a necessary workaround
// see https://stackoverflow.com/a/49821973
template <class T> struct function_traits :
function_traits<decltype(&T::operator())> {};
template <typename ClassType, typename ReturnType, typename... Args>
struct function_traits<ReturnType(ClassType::*)(Args...) const> {
// specialization for pointers to member function
using functor_type = ClassType;
using result_type = ReturnType;
using arg_tuple = std::tuple<Args...>;
static constexpr auto arity = sizeof...(Args);
};
template <class Callable, class... Args>
struct CallableWrapper : Callable, function_traits<Callable> {
CallableWrapper(const Callable &f) : Callable(f) {}
CallableWrapper(Callable &&f) : Callable(std::move(f)) {}
};
template <class F, std::size_t ... Is, class T>
auto wrap_impl(F &&f, std::index_sequence<Is...>, T) {
return CallableWrapper<F, typename T::result_type,
std::tuple_element_t<Is, typename T::arg_tuple>...>(std::forward<F>(f));
}
template <class F> auto wrap(F &&f) {
using traits = function_traits<F>;
return wrap_impl(std::forward<F>(f),
std::make_index_sequence<traits::arity>{}, traits{});
}
int main(int argc, char* argv[]) {
QCoreApplication app(argc, argv);
// a vector of numbers from 0 to 500
QVector<int> seq(500, 0);
std::iota(seq.begin(), seq.end(), 0);
qDebug() << "input: " << seq;
QFuture<int> mapped = QtConcurrent::mapped(seq, wrap([&seq](const int& x) {
// the index of the element in a QVector is the difference between
// the address of the first element in the vector and the address of
// the current element
std::ptrdiff_t idx = std::distance(&seq.at(0), &x);
// we can then use x and idx however we want
return x * idx;
}));
qDebug() << "output: " << mapped.results();
QTimer::singleShot(100, &app, &QCoreApplication::quit);
return app.exec();
}
See this question for a related discussion. Note that the linked question has a cleaner answer that involves the usage of zip and counting iterators from boost (or possibly their C++20 ranges counterparts), but I don't think that this would play well with QtConcurrent::map when map slices the sequence into blocks, and distributes these blocks to multiple threads.

why my my function is using call by value method?

I don't know why in last line it is printing data of first element instead of last element. I want explanation.
// A simple C program for traversal of a linked list
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
// This function prints contents of linked list starting from
// the given node
void printList(struct Node* n)
{
while (n != NULL) {
printf(" %d ", n->data);
n = n->next;
}
}
int main()
{
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
// allocate 3 nodes in the heap
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
head->data = 1; // assign data in first node
head->next = second; // Link first node with second
second->data = 2; // assign data to second node
second->next = third;
third->data = 3; // assign data to third node
third->next = NULL;
printList(head);
printf("%d",head->data);
return 0;
}
As the function is accepting pointers so it should be call by reference.
And in last loop of function when n pointer is equal to NULL.
But in last line of this code is printing data of first list of my linked list.
Actually what you are doing is not being done in the actual linked list, it not pass by reference
void printList(struct Node* n)
{
/* some code here */
}
void main()
{
/* all your code here */
printList(head);
}
so if you want to change the head in the actual linked list you will have to pass the address of the pointer head to the function
something like this
int append_list(node **head, int data)
{
while((*head)->next!=NULL)
{
(*head) = (*head)->next;
}
}
int main()
{
struct node *head = NULL;
/* add nodes */
print_list(&head);
}
so here is the modification in your code:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
// This function prints contents of linked list starting from
// the given node
void printList(struct Node** n)
{
while ((*n)->next != NULL) {
printf(" %d ", (*n)->data);
(*n) = (*n)->next;
}
}
int main()
{
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
// allocate 3 nodes in the heap
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
head->data = 1; // assign data in first node
head->next = second; // Link first node with second
second->data = 2; // assign data to second node
second->next = third;
third->data = 3; // assign data to third node
third->next = NULL;
printList(&head);
printf("%d",head->data);
return 0;
}
here the output will be
1 2 3
since you have used (*head) for the traversal you no longer have the access to your list and hence will get segmentation fault if you try to access
(*head)->next
But I would not suggest to do this since now you will not be able to deallocate the memory
There is no pass-by-reference in C, everything is pass-by-value. People use pointers to emulate pass-by-reference, and this works because you can use the passed-in pointer to get at the same underlying data item.
In other words, even though the passed-in pointer is a pass-by-value copy within the function, the fact that it has the same value as the original means that both point to the same thing.
However, if the thing you're trying to change is a pointer already, you need a pointer to a pointer to do this emulation.
I could give you the code to do this but, believe me, it's not want you want. It would mean that the list printing code would be destructive to the list itself, since the head would now point to NULL.
Here is some code instead which shows how to do something similar, one that uses this double-pointer method to change the pointer outside of the function:
#include <stdio.h>
#include <stdlib.h>
void allocateSomeMem(void **pPtr, size_t sz) {
*pPtr = malloc(sz);
}
int main(void) {
void *x = NULL;
printf("%p\n", x);
allocateSomeMem(&x, 42);
printf("%p\n", x);
}
You can see by the output that the pointer is being changed:
(nil)
0x55f9ce5f96b0
Now, obviously, you wouldn't do this for the simple example shown, it would be far easier just to return the new pointer and have it assigned to x. But this is just illustrative of the method to use.

Class objects destruction

In the following code I intentionally set a pointer, p, to NULL after deleting it so that the second object can't delete it again. However, I recieve the following error dialog in Microsoft Visual C++:
Debug Assertion Failed - Expression: _BLOCK_TYPE_IS_VALID(pHead -> nBlockUse)
Full size image of the error dialog.
#include <iostream>
#include <string>
using namespace std;
class line{
public:
line();
~line();
int* p;
};
line::line(){
p = new int;
}
line::~line()
{
if (p != NULL)
{
delete p;
p = NULL;
}
}
int main()
{
line line1,
line2 = line1;
cout << line1.p << endl << line2.p;
cin.get();
return 0;
}
line1 and line2 are both holding a pointer.
You need to understand that line1.p is a separate variable toline2.p, even though they are pointing to the same address in memory.
Suppose that the line2 destructor is invoked first. It will set line2.p to NULL, but this will not alter the location that line1.p is pointing to.
When the line1 destructor is subsequently invoked, it will attempt to deallocate the already deallocated data that line1.p is pointing to, hence the Debug Assertion.

Printing Address of Struct Element

I have the following struct:
typedef struct Author
{
char** novels;
} Author;
And I want to print the address of an element in the novels array. I tried these two:
printf("%p\n", &(herbert->novels[1]));
printf("%p\n", herbert->novels[1]);
But I'm not sure which is correct. Can someone help me understand which to use and why?
Take a look at the below...
typedef struct Author
{
char** novels;
} Author;
int main()
{
Author a;
char b = 'b';
a.novels = new char*[2];
a.novels[0] = NULL;
a.novels[1] = NULL;
printf("1. %p\n", a.novels[1]);
printf("2. %p\n", &(a.novels[1]));
delete[] a.novels;
return 0;
}
this outputs the following
1. 0000000000000000
2. 00000000001269C8
You can see the first print is actually a NULL - which is the value stored at the a.novels[1].
The second is the address of the a.novels[1] memory.
Assuming you look for the memory address of the item, you'll need the second syntax
printf("%p\n", &(herbert->novels[1]));

passing different structure type in c for functions

I have a following code :
typedef struct PStruct{
int len;
char* data;
}PointerStruct;
typedef struct AStruct{
int len;
char data[256];
}ArrayStruct;
void checkFunc(PointerStruct* myData)
{
if (0 == myData || 0 == myData->data){
printf("error\n");
}
}
int main()
{
ArrayStruct my_data;
my_data.len = 256;
char data[] = "data is sent";
my_data.data = &data;
checkFunc((PointerStruct*)my_data);
return 0;
}
is there any wrong in passing structure which has array. where as the required is pointer.
please let me know.
There are a couple of points to be considered in your program.
char data[] = "data is sent";
This is a character array of 13 characters. Hence, my_data.data = &data; will give a compilation error as shown below
error: incompatible types when assigning to type 'char[256]' from type 'char (*)[13]'
To copy your string, you could probably use strcpy as shown below
strcpy(my_data.data, data);
Next point is passing the pointer to the object. In this call, checkFunc((PointerStruct*)my_data);, you are passing the instance of the object to the function call, but are type-casting as a pointer. You would face compilation issues due to the mismatch of the datatypes as error: cannot convert to a pointer type
To overcome this error, you should pass a reference to your my_data object as checkFunc((PointerStruct*) &my_data);. Hence, your new main function would look like
int main()
{
ArrayStruct my_data;
my_data.len = 256;
char data[] = "data is sent";
//my_data.data = &data;
strcpy(my_data.data, data); // Use of strcpy. You would require to include <string.h>
checkFunc((PointerStruct*)(&my_data)); // Pass a reference and not by value
return 0;
}
With these changes, your code should work fine.

Resources