Search code examples
swiftmacoscocoansxmlelement

XMLElement with tags in between String


I am creating a XML document and trying to insert tags in between XMLElement as below

let tEle = XMLElement.element(withName: "xuv") as? XMLElement
let segEle = XMLElement.element(withName: "seg") as? XMLElement
segEle?.stringValue = "Sample Text Here"
tuvEle?.addChild(segEle!)

This is working fine, but for segEle i want to add some tags between text as "Sample Text <ph x="1" type="x-LPH"/> Here", if we notice i need to insert "ph" tag in between the string.

FYI : I tried to insert " <ph x=\"#\" type=\"x-LPH\"/> " this text between string but this didn't worked as in the output xml file the "ph" tag is displayed as &lt;ph x="0" type="x-LPH"/&gt; OBLIGATOIRE &lt;ph x="1" type="x-LPH"/&gt; (if we notice for "<" it is replaced as "<" and for ">" is replaced as">")

Can anyone please let me know how can we handle this.


Solution

  • Try to backwards-engineer how it's supposed to be: inspect the result of XMLElement(xmlString: "<seg>Sample Text <ph x=\"1\" /> Here") and its children.

    Sample Text <element/> Here
    ^^^^^^^^^^^^~~~~~~~~~~^^^^^
        |          |         |
        |          |         --------- Text node
        |          |
        |          ----- XMLElement
        |
        ----------- Text node
    
    • XMLElement is only suitable for tags;
    • XMLElement.addChild accepts the more general type XMLNode.
    • XMLNode.Kind can be .text, which is what you're looking for instead of the simpler stringValue.

    So you have to split your simple string value into 3 subnodes:

    1. XMLNode.text(withStringValue: "Sample Text ") as? XMLNode
    2. XMLNode.element(withName: "Sample Text ") as? XMLElement
    3. XMLNode.text(withStringValue: " Here") as? XMLNode

    Then add all 3 children to the parent note segEle (which doesn't need a stringValue anymore).