| 630 | |
| 631 | |
| 632 | static int insert_new_node(xmlDoc *doc, xmlNode *parent, xmlDoc *new_doc, xml_path_t *path, str xml_str) |
| 633 | { |
| 634 | xmlNode *new_root, *lead_ws_node, *trail_ws_node; |
| 635 | char lead_ws[64] = {0}, trail_ws[64] = {0}; |
| 636 | char *c; |
| 637 | int lead_ws_len = 0, trail_ws_len = 0; |
| 638 | |
| 639 | /* libxml ignores leading and trailing whitespaces when parsing an XML |
| 640 | * block (if they are not contained IN the root node) so, when adding a |
| 641 | * new node, it would be impossible to insert it with indentation under |
| 642 | * an existing node unless we add the whitespaces manually as nodes in the tree |
| 643 | */ |
| 644 | |
| 645 | /* add leading whitespaces node to existing tree */ |
| 646 | for (c = xml_str.s; c - xml_str.s < xml_str.len && |
| 647 | (*c == ' ' || *c == '\t' || *c == '\n'); c++) |
| 648 | lead_ws[lead_ws_len++] = *c; |
| 649 | |
| 650 | if (lead_ws_len) { |
| 651 | if ((lead_ws_node = xmlNewText(BAD_CAST lead_ws)) == NULL) { |
| 652 | LM_ERR("Unable to create node with leading whitespaces\n"); |
| 653 | return -1; |
| 654 | } |
| 655 | if (!xmlAddChild(parent, lead_ws_node)) { |
| 656 | LM_ERR("Unable to add node with leading whitespaces\n"); |
| 657 | return -1; |
| 658 | } |
| 659 | } |
| 660 | |
| 661 | /* add root of new xml block */ |
| 662 | new_root = xmlDocGetRootElement(new_doc); |
| 663 | xmlSetTreeDoc(new_root, doc); |
| 664 | if (!xmlAddChild(parent, new_root)) { |
| 665 | LM_ERR("Unable to link new xml block into existing tree\n"); |
| 666 | return -1; |
| 667 | } |
| 668 | |
| 669 | /* add trailing whitespaces node */ |
| 670 | c = NULL; |
| 671 | for (c = xml_str.s + xml_str.len - 1; c > xml_str.s && |
| 672 | (*c == ' ' || *c == '\t' || *c == '\n'); c--) ; |
| 673 | trail_ws_len = xml_str.len - (c+1 - xml_str.s); |
| 674 | |
| 675 | if (trail_ws_len) { |
| 676 | memcpy(trail_ws, c+1, trail_ws_len); |
| 677 | |
| 678 | if ((trail_ws_node = xmlNewText(BAD_CAST trail_ws)) == NULL) { |
| 679 | LM_ERR("Unable to create node with trailing whitespaces\n"); |
| 680 | return -1; |
| 681 | } |
| 682 | if (!xmlAddChild(parent, trail_ws_node)) { |
| 683 | LM_ERR("Unable to add node with trailing whitespaces\n"); |
| 684 | return -1; |
| 685 | } |
| 686 | } |
| 687 | |
| 688 | return 0; |
| 689 | } |