XML-тег заменяет, показывая другой результат - PullRequest
2 голосов
/ 08 ноября 2019

Я написал функцию в одном из моих угловых проектов для замены тега другим тегом в XML-файле. Первый параметр - это HTMLElement, второй - searchTag, а третий - replaceTag.

replaceTagWith(xmlCode: HTMLElement, findTag: string, replaceTag: string) {
    // Initializing variables
    let exists: boolean = true;
    let processed: boolean = false;

    while (exists) {
        let sourceTags = xmlCode.querySelector(findTag);

        // If findTag exists
        if (sourceTags) {
            // Setting processed flag
            processed = true;

            // Creating replace tag and setting the textcontent
            let targetTag = document.createElement(replaceTag);
            targetTag.innerHTML = sourceTags.innerHTML;

            // Finding attributes of the tags to be replaced
            let tagAttributes = sourceTags.attributes;
            let attrLength = tagAttributes.length;

            // If there is attributes
            if (attrLength) {
                for (let j = 0; j < attrLength; j++) {

                    // Setting the attribute of replace tag
                    targetTag.setAttribute(tagAttributes[j].name, tagAttributes[j].value);
                }
            }

            // Appending the target tag just before the source tag
            sourceTags.parentNode.insertBefore(targetTag, sourceTags);

            // Removing findTag
            sourceTags.parentNode.removeChild(sourceTags);

        } else {
            exists = false;
        }
    }

Эта функция хорошо работает, когда я заменяю тег <title> на <sec-title>. Вот вызов функции ..

const parser = new DOMParser();
const xml = parser.parseFromString(this.xmlData, 'application/xml');
let xmlCode: any = xml.documentElement;
this.replaceTagWith(xmlCode, 'title', 'sec-title');

результат будет таким:

<sec-title xmlns="http://www.w3.org/1999/xhtml">What is Child Protection<named-content xmlns="http://www.w3.org/1999/xhtml" content-type="index" name="default" a-level="child protection" b-level="definition of" c-level="" d-level="" e-level="" format="" range="" see="" see-also=""></named-content> in Humanitarian Action? </sec-title>

Но проблема в том, что когда я пытаюсь заменить <sec-title> на <title>,результат, показывающий:

<title xmlns="http://www.w3.org/1999/xhtml">What is Child Protection&lt;named-content xmlns="http://www.w3.org/1999/xhtml" content-type="index" name="default" a-level="child protection" b-level="definition of" c-level="" d-level="" e-level="" format="" range="" see="" see-also=""&gt;&lt;/named-content&gt; in Humanitarian Action? </title>

теги html (здесь <named-content>) внутри <title> заменяются на &lt;named-content&gt;

Это часть xml, с которой я работаю ..

<sec level="2" id="sec002" sec-type="level-B">
    <title xmlns="http://www.w3.org/1999/xhtml">What is Child Protection<named-content content-type="index"
            name="default" a-level="child protection" b-level="definition of" c-level="" d-level="" e-level=""
            format="" range="" see="" see-also=""></named-content> in Humanitarian Action? </title>
    <p specific-use="para">Child protection is the ‘prevention of and response to abuse, neglect, exploitation and
        violence against children’.</p>
    <p specific-use="para">The objectives of humanitarian action are to:</p>
    <list list-type="bullet" specific-use="1" list-content="Lijstalinea">
        <list-item>
            <p specific-use="para">Save lives, alleviate suffering and maintain human dignity during and after
                disasters; and</p>
        </list-item>
        <list-item>
            <p specific-use="para">Strengthen preparedness for any future crises.</p>
        </list-item>
    </list>
    <p specific-use="para">Humanitarian crises<named-content xmlns="http://www.w3.org/1999/xhtml"
            content-type="index" name="default" a-level="humanitarian crises" b-level="causes of" c-level=""
            d-level="" e-level="" format="" range="" see="" see-also=""></named-content> can be caused by humans,
        such as conflict or civil unrest; they can result from disasters, such as floods and earthquakes; or they
        can be a combination of both.</p>
    <p specific-use="para">Humanitarian crises<named-content xmlns="http://www.w3.org/1999/xhtml"
            content-type="index" name="default" a-level="humanitarian crises" b-level="effects on children of"
            c-level="" d-level="" e-level="" format="" range="" see="" see-also=""></named-content>
        often have long-lasting, devastating effects on children’s lives. The child protection risks children face
        include family separation, recruitment into armed forces or groups, physical or sexual abuse, psychosocial
        distress or mental disorders, economic exploitation, injury and even death. They depend on factors such as
        the:</p>
    <list list-type="bullet" specific-use="1" list-content="Lijstalinea">
        <list-item>
            <p specific-use="para">Nature and scale of the emergency;</p>
        </list-item>
        <list-item>
            <p specific-use="para">Number of children affected;</p>
        </list-item>
        <list-item>
            <p specific-use="para">Sociocultural norms;</p>
        </list-item>
        <list-item>
            <p specific-use="para">Pre-existing child protection risks;</p>
        </list-item>
        <list-item>
            <p specific-use="para">Community-level preparedness; and</p>
        </list-item>
        <list-item>
            <p specific-use="para">Stability and capacity of the State before and during the crisis.</p>
        </list-item>
    </list>
    <p specific-use="para">Child protection actors and interventions seek to prevent and respond to all forms of
        abuse, neglect, exploitation and violence. Effective child protection builds on existing capacities and
        strengthens preparedness before a crisis occurs. During humanitarian crises, timely interventions support
        the physical and emotional health, dignity and well-being of children, families and communities.</p>
    <p specific-use="para">Child protection in humanitarian action includes specific activities conducted by local,
        national and international child protection actors. It also includes efforts of non-child protection actors
        who seek to prevent and address abuse, neglect, exploitation and violence against children in humanitarian
        settings, whether through mainstreamed or integrated programming.</p>
    <p specific-use="para">Child Protection in Humanitarian Action promotes the well-being and healthy development
        of children and saves lives.</p>
</sec>

Чтобы отобразить этот код в более широком формате, сначала я заменил тег <title> на <sec-title>, и он работает нормально. Наконец, на этапе экспорта xml я заменил обратно <sec-title> на <title>. Вот этап, на котором возникает проблема ...

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...