2

I am working on replace xml node. I have problem in remove parent node with inner node itself.

I want to remove parent node with few inner node and retain some other inner nodes.

The Source of the xml string:

 <root>
 ***<bPoint id="1" >
       <bLabel>
            <text></text>
       </bLabel>
       <content src="p112" />***
       <bPoint id="2">
           <bLabel>
               <text>xxx</text>
           </bLabel>
           <content src="p1123" />
       </bPoint>
 ***</bPoint>***
     <bPoint id="bPoint-2" >
         <bLabel>
             <text>xxx</text>
         </bLabel>
           <content src="p1123" />        
    </bPoint>
 </root>

My Output will be

<root>
<bPoint id="2">
     <bLabel>
        <text>xxx</text>
     </bLabel>
      <content src="p1123" />
 </bPoint>
<bPoint id="bPoint-2" >
   <bLabel>
         <text>xxx</text>
   </bLabel>
   <content src="p1123" />         
</bPoint>
</root>

Any one assist me?

Thanks in advance.

1 Answer 1

2

You can use the replaceChild method on the parent node of the node you want to replace.

so you would want to do a replaceChild on root passing in your bPoint with id 2 as the first argument and bPoint with id 1 as the second

rootNode.replaceChild(bPoint2,bPoint1);

Demo

var xml = '<?xml version="1.0" encoding="ISO-8859-1" ?><root><bPoint id="1"><bLabel><text></text></bLabel><content src="p112" /><bPoint id="2"><bLabel><text>xxx</text></bLabel><content src="p1123" /></bPoint></bPoint><bPoint id="bPoint-2" ><bLabel><text>xxx</text></bLabel><content src="p1123" /></bPoint></root>'

//Create xml parser and parse to XMLDocument
var parser = new DOMParser();
var xmldoc = parser.parseFromString(xml,"text/xml");

//Get "root" node
var rootNode = xmldoc.querySelector("root");

//Would use id selectors but number ids are invalid selectors
var bPoint1 = xmldoc.querySelector("bPoint");
var bPoint2 = bPoint1.querySelector("bPoint");

//Replace bPoint 1 with bPoint2
rootNode.replaceChild(bPoint2,bPoint1);

//Get the new xml string
var newXml = (new XMLSerializer).serializeToString(xmldoc);

console.log(xmldoc);
document.body.innerText = newXml;

Sign up to request clarification or add additional context in comments.

2 Comments

If i have more bPoint inside, How to replace multiple bPoint into single bPoint?
The question was tagged with node.js. So what package does support xmldoc.querySelector?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.