How to read and create child nodes using XmlReader

400 views Asked by At

I have a xml file. I trying generate a new xml file from that old xml file with some modification.

I have xml like this

<Parent>
<child>
  <child 1 />
  <child 2 />
  <child 3>
      <child A1 />
      <child A2 />
      <child A3 />
  </child 3 >
  <child 4 />
  <child 5 />
</child>
<Parent>

I trying to generate a new xml file like this

<Parent>
 <Child>
  <child 1/>
  <child 3/>
  <child 3/>
      <child A1 />
      <child A2 />
      <child A3 />
  </child 3 >
  <child 4 />
  <child 5 />
 </Child>
 <Child>
  <child 1 />
  <child 2 />
  <child 3>
      <child A1 />
      <child A2 />
      <child A3 />
  </child 3 >
  <child 4 />
  <child 5 />
 </Child>
</Parent>

I tried below code

XmlReader xmlreader;
if (xmlTextReader.ReadToFollowing("Parent"))  
{                   
 XmlReader inner = xmlTextReader.ReadSubtree();
 while (isStartElement)
 {
 inner.Read();
 switch (xmlTextReader.NodeType)
 {
 case XmlNodeType.Element:
     xmlreader = inner.ReadSubtree();                           
     xmlreader.ReadToDescendant("Parent");
     xmlreader.Read();

     do
     {
       if (xmlTextReader.Name != "Parent")
       {
          xmlTextWriter.WriteStartElement(xmlTextReader.Prefix, xmlTextReader.LocalName,xmlTextReader.NamespaceURI);
       }
       if (xmlTextReader.HasAttributes)
       {
            while (xmlTextReader.MoveToNextAttribute())
            {
              xmlTextWriter.WriteAttributeString(xmlTextReader.Name,xmlTextReader.Value.ToString());
            }
        }

     xmlTextWriter.WriteEndElement();

   } while (inner.ReadToNextSibling("Child"));                              

    break;
  }
 }
}

I tried above code but it get only return below xml

<Child />
<Child />

It return on parent node of child1 child2 etc. nodes

I am using 2 xmlreader for read the xml

I need below xml output like

<Child>
  <child 1/>
  <child 3/>
  <child 3/>
      <child A1 />
      <child A2 />
      <child A3 />
  </child 3 >
  <child 4 />
  <child 5 />
 </Child>
 <Child>
  <child 1 />
  <child 2 />
  <child 3>
      <child A1 />
      <child A2 />
      <child A3 />
  </child 3 >
  <child 4 />
  <child 5 />
 </Child>

I need some code in do while for getting child nodes and then close the parent node. so i will get desire output

0

There are 0 answers