Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Manipulate XML

Manipulate XML

Scheduled Pinned Locked Moved C#
xmltutorialquestionannouncement
11 Posts 2 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • N Offline
    N Offline
    NarVish
    wrote on last edited by
    #1

    Hi, In the below XML file, I would like add an element studentMarks with attribute Total=100, where the Student ID=101. I tried with InsertAfter method, but it didn't work. Please guide me, Thanks in advance.

    <? xml version = “1.0″ encoding = “UTF-8″?>
    <StudentRecords>
    <SpecialStudent id=555>
    <StudentName> John Trivolta </StudentName>
    <StudentSubject> Science </StudentSubject>
    <SpecialStudent>
    <Student ID=100>
    <StudentName> John Trivolta </StudentName>
    <StudentSubject> Science </StudentSubject>
    </Student>
    <Student ID=101>
    <StudentName> Bruce Lee </StudentName>
    <StudentSubject> Computer </StudentSubject>
    </Student>
    <Student ID=102>
    <StudentName> North V </StudentName>
    <StudentSubject> Maths</StudentSubject>
    </Student>
    <StudentRecords>

    N 1 Reply Last reply
    0
    • N NarVish

      Hi, In the below XML file, I would like add an element studentMarks with attribute Total=100, where the Student ID=101. I tried with InsertAfter method, but it didn't work. Please guide me, Thanks in advance.

      <? xml version = “1.0″ encoding = “UTF-8″?>
      <StudentRecords>
      <SpecialStudent id=555>
      <StudentName> John Trivolta </StudentName>
      <StudentSubject> Science </StudentSubject>
      <SpecialStudent>
      <Student ID=100>
      <StudentName> John Trivolta </StudentName>
      <StudentSubject> Science </StudentSubject>
      </Student>
      <Student ID=101>
      <StudentName> Bruce Lee </StudentName>
      <StudentSubject> Computer </StudentSubject>
      </Student>
      <Student ID=102>
      <StudentName> North V </StudentName>
      <StudentSubject> Maths</StudentSubject>
      </Student>
      <StudentRecords>

      N Offline
      N Offline
      NavnathKale
      wrote on last edited by
      #2

      1. Get the XMLNode Student (of ID 101) 2. Get XMLNode StudentSubject 3. Call InsertAfter of Student node and pass StudentSubject node as reference node 4. And don't forget to save document If you this didn't help, post ur code here to analyse ;)

      N 1 Reply Last reply
      0
      • N NavnathKale

        1. Get the XMLNode Student (of ID 101) 2. Get XMLNode StudentSubject 3. Call InsertAfter of Student node and pass StudentSubject node as reference node 4. And don't forget to save document If you this didn't help, post ur code here to analyse ;)

        N Offline
        N Offline
        NarVish
        wrote on last edited by
        #3

        Thanks for the reply. Please look at my code. I'm getting exception at below line. xmlDoc.DocumentElement.InsertAfter(newcatalogentry, refNode); Exception message: "The reference node is not a child of this node."

        XmlTextReader xmlReader = new XmlTextReader(Application.StartupPath + "\\doc.xml");
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(xmlReader);
        xmlReader.Close();

                string xpath = string.Format("/StudentRecords/Student");
                XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
                XmlNodeList fieldNodes = xmlDoc.SelectNodes(xpath, nsmgr);
                string refName = "";
                int index = 0;
                XmlAttributeCollection ddd;
                XmlNode refNode = null;
                string studentID;
                foreach (XmlNode node in fieldNodes)
                {
                    ddd = fieldNodes\[index\].Attributes;
                    studentID = ddd\["ID"\].Value.ToString();
                    
                    if (Convert.ToInt32(studentID) == 101)
                    {
                        refNode = node.SelectSingleNode("StudentSubject");
                    }
                }
                XmlDocument xmldoc = new XmlDocument();
                XmlElement newcatalogentry = xmldoc.CreateElement("StudentMarks");
                XmlAttribute newcatalogattr = xmldoc.CreateAttribute("Total");
        
                newcatalogattr.Value = "100";
        
                // Attach the attribute to the XML element
                newcatalogentry.SetAttributeNode(newcatalogattr);
        
        
        
                // New XML element inserted into the document
                xmlDoc.DocumentElement.InsertAfter(newcatalogentry, refNode);
                string path = "C:\\\\test.xml";
                FileStream fsxml = new FileStream(path, FileMode.Truncate,
                                                  FileAccess.Write,
                                                  FileShare.ReadWrite);
                xmlDoc.Save(path);
        
        N 1 Reply Last reply
        0
        • N NarVish

          Thanks for the reply. Please look at my code. I'm getting exception at below line. xmlDoc.DocumentElement.InsertAfter(newcatalogentry, refNode); Exception message: "The reference node is not a child of this node."

          XmlTextReader xmlReader = new XmlTextReader(Application.StartupPath + "\\doc.xml");
          XmlDocument xmlDoc = new XmlDocument();
          xmlDoc.Load(xmlReader);
          xmlReader.Close();

                  string xpath = string.Format("/StudentRecords/Student");
                  XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
                  XmlNodeList fieldNodes = xmlDoc.SelectNodes(xpath, nsmgr);
                  string refName = "";
                  int index = 0;
                  XmlAttributeCollection ddd;
                  XmlNode refNode = null;
                  string studentID;
                  foreach (XmlNode node in fieldNodes)
                  {
                      ddd = fieldNodes\[index\].Attributes;
                      studentID = ddd\["ID"\].Value.ToString();
                      
                      if (Convert.ToInt32(studentID) == 101)
                      {
                          refNode = node.SelectSingleNode("StudentSubject");
                      }
                  }
                  XmlDocument xmldoc = new XmlDocument();
                  XmlElement newcatalogentry = xmldoc.CreateElement("StudentMarks");
                  XmlAttribute newcatalogattr = xmldoc.CreateAttribute("Total");
          
                  newcatalogattr.Value = "100";
          
                  // Attach the attribute to the XML element
                  newcatalogentry.SetAttributeNode(newcatalogattr);
          
          
          
                  // New XML element inserted into the document
                  xmlDoc.DocumentElement.InsertAfter(newcatalogentry, refNode);
                  string path = "C:\\\\test.xml";
                  FileStream fsxml = new FileStream(path, FileMode.Truncate,
                                                    FileAccess.Write,
                                                    FileShare.ReadWrite);
                  xmlDoc.Save(path);
          
          N Offline
          N Offline
          NavnathKale
          wrote on last edited by
          #4

          XmlDocument xmlDoc = new XmlDocument();
          xmlDoc.Load(Application.StartupPath + "\\doc.xml");

                  string xpath = string.Format("/StudentRecords/Student");
                  XmlNodeList fieldNodes = xmlDoc.SelectNodes(xpath);
          
                  XmlNode studentNode = null;
                  XmlNode refNode = null;
                  
                  foreach (XmlNode node in fieldNodes)
                  {
                      if (node.Attributes\["ID"\].Value == "101")
                      {
                          studentNode = node;
                          refNode = node.SelectSingleNode("StudentSubject");
                      }
                  }
          
                  if (studentNode != null && refNode != null)
                  {
                      XmlElement newcatalogentry = xmlDoc.CreateElement("StudentMarks");
                      XmlAttribute newcatalogattr = xmlDoc.CreateAttribute("Total");
          
                      newcatalogattr.Value = "100";
          
                      // Attach the attribute to the XML element
                      newcatalogentry.SetAttributeNode(newcatalogattr);
          
                      // New XML element inserted into the document
                      studentNode.InsertAfter(newcatalogentry, refNode);
          
                      string path = "C:\\\\test.xml";
                      
                      xmlDoc.Save(path);
                  }
          

          updated within post area, test it at your end :cool:

          N 2 Replies Last reply
          0
          • N NavnathKale

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(Application.StartupPath + "\\doc.xml");

                    string xpath = string.Format("/StudentRecords/Student");
                    XmlNodeList fieldNodes = xmlDoc.SelectNodes(xpath);
            
                    XmlNode studentNode = null;
                    XmlNode refNode = null;
                    
                    foreach (XmlNode node in fieldNodes)
                    {
                        if (node.Attributes\["ID"\].Value == "101")
                        {
                            studentNode = node;
                            refNode = node.SelectSingleNode("StudentSubject");
                        }
                    }
            
                    if (studentNode != null && refNode != null)
                    {
                        XmlElement newcatalogentry = xmlDoc.CreateElement("StudentMarks");
                        XmlAttribute newcatalogattr = xmlDoc.CreateAttribute("Total");
            
                        newcatalogattr.Value = "100";
            
                        // Attach the attribute to the XML element
                        newcatalogentry.SetAttributeNode(newcatalogattr);
            
                        // New XML element inserted into the document
                        studentNode.InsertAfter(newcatalogentry, refNode);
            
                        string path = "C:\\\\test.xml";
                        
                        xmlDoc.Save(path);
                    }
            

            updated within post area, test it at your end :cool:

            N Offline
            N Offline
            NarVish
            wrote on last edited by
            #5

            Thank you very much :)

            1 Reply Last reply
            0
            • N NavnathKale

              XmlDocument xmlDoc = new XmlDocument();
              xmlDoc.Load(Application.StartupPath + "\\doc.xml");

                      string xpath = string.Format("/StudentRecords/Student");
                      XmlNodeList fieldNodes = xmlDoc.SelectNodes(xpath);
              
                      XmlNode studentNode = null;
                      XmlNode refNode = null;
                      
                      foreach (XmlNode node in fieldNodes)
                      {
                          if (node.Attributes\["ID"\].Value == "101")
                          {
                              studentNode = node;
                              refNode = node.SelectSingleNode("StudentSubject");
                          }
                      }
              
                      if (studentNode != null && refNode != null)
                      {
                          XmlElement newcatalogentry = xmlDoc.CreateElement("StudentMarks");
                          XmlAttribute newcatalogattr = xmlDoc.CreateAttribute("Total");
              
                          newcatalogattr.Value = "100";
              
                          // Attach the attribute to the XML element
                          newcatalogentry.SetAttributeNode(newcatalogattr);
              
                          // New XML element inserted into the document
                          studentNode.InsertAfter(newcatalogentry, refNode);
              
                          string path = "C:\\\\test.xml";
                          
                          xmlDoc.Save(path);
                      }
              

              updated within post area, test it at your end :cool:

              N Offline
              N Offline
              NarVish
              wrote on last edited by
              #6

              In the below xml, I would like to add this element

              <StudentClass ref="F_GAMES" />

              after

              <StudentClass ref="F_STRENGTH" />

              where student id=101. The below code is Please correct the below code.. its wrongly updating the xml. Thanks in advance..

              <?xml version="1.0"?>
              <StudentRecords>
              <Student ID="100">
              <StudentClass id="XA" name="XA" >
              <StudentClass ref="F_HEIGHT" />
              <StudentClass ref="F_WEIGHT" />
              <StudentClass ref="F_STRENGTH" />
              <StudentClass ref="F_LIBRARY" />
              <StudentClass ref="F_QUALIFIER" />
              </StudentClass>
              </Student>
              <Student ID="101">
              <StudentClass id="XB" name="XB" >
              <StudentClass ref="F_HEIGHT" />
              <StudentClass ref="F_WEIGHT" />
              <StudentClass ref="F_STRENGTH" />
              <StudentClass ref="F_LIBRARY" /> </StudentClass>
              </Student>
              </StudentRecords>

              XmlDocument xmlDoc = new XmlDocument();
              xmlDoc.Load(Application.StartupPath :-D + "\\doc.xml");
              string xpath = string.Format("/StudentRecords/Student");
              XmlNodeList fieldNodes = xmlDoc.SelectNodes(xpath);
              XmlNode studentNode = null;
              XmlNode refNode = null;
              foreach (XmlNode node in fieldNodes)
              {
              if (node.Attributes["ID"].Value == "101")
              {
              fieldNodes = xmlDoc.SelectNodes(xpath + "/StudentClass");
              XmlNode node1 = fieldNodes.Item(0);
              studentNode = node1;
              refNode = node1.SelectSingleNode("StudentClass");
              break;
              }

                      }            
                      if (studentNode != null && refNode != null)            
                      {
                          XmlElement newcatalogentry = xmlDoc.CreateElement("StudentClass");
                          XmlAttribute newcatalogattr = xmlDoc.CreateAttribute("ref");            
                          newcatalogattr.Value = "F\_NewCategory";                
                          // Attach the attribute to the XML element                
                          newcatalogentry.SetAttributeNode(newcatalogattr);                
                          // New XML element inserted into the document                
                          studentNode.Inse
              
              N 1 Reply Last reply
              0
              • N NarVish

                In the below xml, I would like to add this element

                <StudentClass ref="F_GAMES" />

                after

                <StudentClass ref="F_STRENGTH" />

                where student id=101. The below code is Please correct the below code.. its wrongly updating the xml. Thanks in advance..

                <?xml version="1.0"?>
                <StudentRecords>
                <Student ID="100">
                <StudentClass id="XA" name="XA" >
                <StudentClass ref="F_HEIGHT" />
                <StudentClass ref="F_WEIGHT" />
                <StudentClass ref="F_STRENGTH" />
                <StudentClass ref="F_LIBRARY" />
                <StudentClass ref="F_QUALIFIER" />
                </StudentClass>
                </Student>
                <Student ID="101">
                <StudentClass id="XB" name="XB" >
                <StudentClass ref="F_HEIGHT" />
                <StudentClass ref="F_WEIGHT" />
                <StudentClass ref="F_STRENGTH" />
                <StudentClass ref="F_LIBRARY" /> </StudentClass>
                </Student>
                </StudentRecords>

                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(Application.StartupPath :-D + "\\doc.xml");
                string xpath = string.Format("/StudentRecords/Student");
                XmlNodeList fieldNodes = xmlDoc.SelectNodes(xpath);
                XmlNode studentNode = null;
                XmlNode refNode = null;
                foreach (XmlNode node in fieldNodes)
                {
                if (node.Attributes["ID"].Value == "101")
                {
                fieldNodes = xmlDoc.SelectNodes(xpath + "/StudentClass");
                XmlNode node1 = fieldNodes.Item(0);
                studentNode = node1;
                refNode = node1.SelectSingleNode("StudentClass");
                break;
                }

                        }            
                        if (studentNode != null && refNode != null)            
                        {
                            XmlElement newcatalogentry = xmlDoc.CreateElement("StudentClass");
                            XmlAttribute newcatalogattr = xmlDoc.CreateAttribute("ref");            
                            newcatalogattr.Value = "F\_NewCategory";                
                            // Attach the attribute to the XML element                
                            newcatalogentry.SetAttributeNode(newcatalogattr);                
                            // New XML element inserted into the document                
                            studentNode.Inse
                
                N Offline
                N Offline
                NavnathKale
                wrote on last edited by
                #7
                        foreach (XmlNode node in fieldNodes)            
                        {
                            if (node.Attributes\["ID"\].Value == "101")    
                            {
                                fieldNodes = node.SelectNodes("/StudentClass");
                
                                if (fieldNodes != null && fieldNodes.Count > 0)
                                {
                                    studentNode = fieldNodes.Item(0);
                
                                    //loop thrugh all childNodes to get node with ref=F\_STRENGTH
                                    foreach (XmlNode nodeClass in studentNode.ChildNodes)
                                    {
                                        if (nodeClass.Attributes\["ref"\].Value == "F\_STRENGTH")
                                        {
                                            refNode = nodeClass;
                                            break;
                                        }
                                    }
                                }
                                break;
                            }                       
                        }
                
                N 1 Reply Last reply
                0
                • N NavnathKale
                          foreach (XmlNode node in fieldNodes)            
                          {
                              if (node.Attributes\["ID"\].Value == "101")    
                              {
                                  fieldNodes = node.SelectNodes("/StudentClass");
                  
                                  if (fieldNodes != null && fieldNodes.Count > 0)
                                  {
                                      studentNode = fieldNodes.Item(0);
                  
                                      //loop thrugh all childNodes to get node with ref=F\_STRENGTH
                                      foreach (XmlNode nodeClass in studentNode.ChildNodes)
                                      {
                                          if (nodeClass.Attributes\["ref"\].Value == "F\_STRENGTH")
                                          {
                                              refNode = nodeClass;
                                              break;
                                          }
                                      }
                                  }
                                  break;
                              }                       
                          }
                  
                  N Offline
                  N Offline
                  NarVish
                  wrote on last edited by
                  #8

                  The value of fieldNodes.Count is 0. so the condition failed in the below if condition

                  if (fieldNodes != null && fieldNodes.Count > 0)

                  N 1 Reply Last reply
                  0
                  • N NarVish

                    The value of fieldNodes.Count is 0. so the condition failed in the below if condition

                    if (fieldNodes != null && fieldNodes.Count > 0)

                    N Offline
                    N Offline
                    NavnathKale
                    wrote on last edited by
                    #9

                    check line fieldNodes = node.SelectNodes("/StudentClass"); see other ways to get all StudentClass if it fails. else try this

                            foreach (XmlNode node in fieldNodes)            
                            {
                                if (node.Attributes\["ID"\].Value == "101")    
                                {
                                    studentNode = node\["StudentClass"\];
                    
                                    if(studentNode != null)
                                    {
                                        //loop thrugh all childNodes to get node with ref=F\_STRENGTH
                                        foreach (XmlNode nodeClass in studentNode.ChildNodes)
                                        {
                                            if (nodeClass.Attributes\["ref"\].Value == "F\_STRENGTH")
                                            {
                                                refNode = nodeClass;
                                                break;
                                            }
                                        }
                                    }
                                    break;
                                }                       
                            }
                    
                    N 1 Reply Last reply
                    0
                    • N NavnathKale

                      check line fieldNodes = node.SelectNodes("/StudentClass"); see other ways to get all StudentClass if it fails. else try this

                              foreach (XmlNode node in fieldNodes)            
                              {
                                  if (node.Attributes\["ID"\].Value == "101")    
                                  {
                                      studentNode = node\["StudentClass"\];
                      
                                      if(studentNode != null)
                                      {
                                          //loop thrugh all childNodes to get node with ref=F\_STRENGTH
                                          foreach (XmlNode nodeClass in studentNode.ChildNodes)
                                          {
                                              if (nodeClass.Attributes\["ref"\].Value == "F\_STRENGTH")
                                              {
                                                  refNode = nodeClass;
                                                  break;
                                              }
                                          }
                                      }
                                      break;
                                  }                       
                              }
                      
                      N Offline
                      N Offline
                      NarVish
                      wrote on last edited by
                      #10

                      Thank you, it worked..

                      N 1 Reply Last reply
                      0
                      • N NarVish

                        Thank you, it worked..

                        N Offline
                        N Offline
                        NavnathKale
                        wrote on last edited by
                        #11

                        my pleasure :-D

                        1 Reply Last reply
                        0
                        Reply
                        • Reply as topic
                        Log in to reply
                        • Oldest to Newest
                        • Newest to Oldest
                        • Most Votes


                        • Login

                        • Don't have an account? Register

                        • Login or register to search.
                        • First post
                          Last post
                        0
                        • Categories
                        • Recent
                        • Tags
                        • Popular
                        • World
                        • Users
                        • Groups