none
Assigning values to XML Elements & Attributes in C#

    Question

  • Hi All,

    I need to know how do we assign values to xml elements/attributes using C# and the structure of the XML document is predefined. I need to load the XML document from the file system and then populate xml elements/attributes with values I would fetch from an external assembly.

    Please do let me know. Thanks

    Tuesday, December 14, 2010 10:54 AM

Answers

  • Am i the only one who thinks the System.Xml syntax looks like rubbish??

     

    Use System.Xml.Linq,

    private void CreateXmlDoc(string path)
     {
      // Load File
      XElement doc = XElement.Load(path);
    
      // Create new node, notice the indentation, The coding should
      // match the layout of your xml file. Just makes things easier!
      XElement newNode = new XElement("Person", new XAttribute("Name", "Tux"),
        new XElement("Age", 34),
        new XElement("Children", 1),
        new XElement("Married", false),
        new XElement("Pets",
          new XElement("Cats", "Billy,Fluffy"),
          new XElement("Dogs", "null")));
    
      // Add new person
      doc.Add(newNode);
    
      // Loop all people, assuming root is named "People"
      foreach (var person in doc.Elements("People")) ;
    
      // Grab a specific person
      string personToGet = "Tux";
      var me = doc.Elements("Person").Where(name => name.Attribute("Name").ToString() == personToGet);
     }
    

     

    Tuesday, December 14, 2010 3:34 PM

All replies

  • hi,

    void CreateXmlFile(String xmlFilePath)
        {
          XmlTextWriter xmlWriter = new XmlTextWriter(xmlFilePath, Encoding.UTF8);
          xmlWriter.WriteStartDocument(true);
          xmlWriter.WriteStartElement("Departments"); //Root Element
          xmlWriter.WriteStartElement("Department"); //Department Element
    
          xmlWriter.WriteStartAttribute("Name"); //Attribute "Name"
          xmlWriter.WriteString("Development"); //Attribute Value 
          xmlWriter.WriteEndAttribute();
    
          xmlWriter.WriteStartElement("Employees"); //Started Employees Element
          xmlWriter.WriteStartElement("Employee"); //Started Employee Element
    
          xmlWriter.WriteStartAttribute("Name"); //Attribute "Name"
          xmlWriter.WriteString("Sabu C.Alex"); //Attribute Value 
          xmlWriter.WriteEndAttribute();
    
          xmlWriter.WriteStartAttribute("Age");//Attribute "Age"
          xmlWriter.WriteString("28");//Attribute Value
          xmlWriter.WriteEndAttribute();
          xmlWriter.WriteString("Sabu C.Alex is working as a Software Engineer"); //Employee Element Inner Text
          xmlWriter.WriteEndElement(); //End of Employee Element
    
          xmlWriter.WriteStartElement("Employee"); //Started Employee Element
          xmlWriter.WriteStartAttribute("Name"); //Attribute "Name"
          xmlWriter.WriteString("Dinup Varghese"); //Attribute Value 
          xmlWriter.WriteEndAttribute();
          xmlWriter.WriteStartAttribute("Age");//Attribute "Age"
          xmlWriter.WriteString("28");//Attribute Value
          xmlWriter.WriteEndAttribute();
          xmlWriter.WriteString("Dinup Varghese is working as a Software Engineer"); //Employee Element Inner Text
          xmlWriter.WriteEndElement(); //End of Employee Element
          xmlWriter.WriteEndElement(); //End of Employees Element
          xmlWriter.WriteEndElement(); //End of Department Element
    
    
          xmlWriter.WriteStartElement("Department"); //Department Element
    
          xmlWriter.WriteStartAttribute("Name"); //Attribute "Name"
          xmlWriter.WriteString("Accounts"); //Attribute Value 
          xmlWriter.WriteEndAttribute();
    
          xmlWriter.WriteStartElement("Employees"); //Started Employees Element
          xmlWriter.WriteStartElement("Employee"); //Started Employee Element
    
          xmlWriter.WriteStartAttribute("Name"); //Attribute "Name"
          xmlWriter.WriteString("Mathew"); //Attribute Value 
          xmlWriter.WriteEndAttribute();
    
          xmlWriter.WriteStartAttribute("Age");//Attribute "Age"
          xmlWriter.WriteString("28");//Attribute Value
          xmlWriter.WriteEndAttribute();
          xmlWriter.WriteString("Mathew is working as an Account"); //Employee Element Inner Text
          xmlWriter.WriteEndElement(); //End of Employee Element
    
          xmlWriter.WriteStartElement("Employee"); //Started Employee Element
          xmlWriter.WriteStartAttribute("Name"); //Attribute "Name"
          xmlWriter.WriteString("Edwin"); //Attribute Value 
          xmlWriter.WriteEndAttribute();
          xmlWriter.WriteStartAttribute("Age");//Attribute "Age"
          xmlWriter.WriteString("28");//Attribute Value
          xmlWriter.WriteEndAttribute();
          xmlWriter.WriteString("Edwin is working as a Junior Accountant"); //Employee Element Inner Text
          xmlWriter.WriteEndElement(); //End of Employee Element
          xmlWriter.WriteEndElement(); //End of Employees Element
          xmlWriter.WriteEndElement(); //End of Department Element
          xmlWriter.WriteEndElement(); //End of Root Element
          xmlWriter.WriteEndDocument();
          xmlWriter.Flush();
          xmlWriter.Close();
        }
    


    Nagarjuna Dilip
    Tuesday, December 14, 2010 11:00 AM
  • Open the XML Document:

     

    string xmlFile = fileOpenDialog.FileName;

     

                        XmlReader xmlReader = null;
                        XmlReaderSettings xmlReaderSettings = new XmlReaderSettings();
                        XmlDocument xmlDoc = new XmlDocument();

     

                        //XML Document validation through Schema.
                        xmlReaderSettings.Schemas.Add(null, XML_SCHEMA_DEFAULT_PATH);
                        xmlReaderSettings.ValidationEventHandler += new ValidationEventHandler(ValidationEventHandler);
                        xmlReaderSettings.ValidationType = ValidationType.Schema;

                        xmlReaderSettings.IgnoreWhitespace = true;
                        xmlReaderSettings.IgnoreComments = true;

                        //Load the user Configuration File.
                        xmlReader = XmlReader.Create(xmlFile, xmlReaderSettings);
                        xmlDoc.Load(xmlReader);
                        xmlReader.Close();

                        //Validate the XML file for any format errors

                        xmlDoc.Validate(ValidationEventHandler);

    //To read a node from XML:

    XmlNode myNode= xmlDoc.CreateElement("myElement");

    //Set a value to an attribute.

    myNode.SetAttribute("Att_Name",Value);

     

    //Add the node to document

    xmlDoc.AppendChild(myNpde);

     

    //To save

    xmlDoc.Save(fileName);

     

    Hope this helps :)

     

     

    Tuesday, December 14, 2010 11:03 AM
  • hi,

    u can try this also

    using System.Xml; 
    
    
    void CreateXML()
    {
      XmlDocument xmldoc = new XmlDocument();
      XmlNode xmlRoot, xmlNode;
      xmlRoot = xmldoc.CreateElement("Root");
    
      xmldoc.AppendChild(xmlRoot);
      xmlNode = xmldoc.CreateElement("Child");
      xmlRoot.AppendChild(xmlNode);
      xmlNode.InnerText = "This is the first Child";
     // you can also take a textbox instead of the text like this;
     // xmlNode.InnerText = TextBox1.Text;
    
      xmlNode = xmldoc.CreateElement("Child2");
      xmlRoot.AppendChild(xmlNode);
      xmlNode.InnerText = "This is the second Child";
    
      xmlNode = xmldoc.CreateElement("Child3");
      xmlRoot.AppendChild(xmlNode);
      xmlNode.InnerText = "This is the third Child";
     // you can make as many childs as you want 
      string filename = @"c:\" + DateTime.Now.Day + DateTime.Now.Month + DateTime.Now.Year + ".xml";
     // i wanted the date as the filename, so i can see when it was created
     // of course you can change it to: 
     // string filename = @"c:\NewXML" + ".xml" or @"c:\whatever" + ".xml"
    
      xmldoc.Save(filename);
    
    }
    


    Nagarjuna Dilip
    Tuesday, December 14, 2010 11:03 AM
  • Hi All,

    Thanks for the reply.

    But I don't need to create an XML Document from scratch, I load the XML Document from the filesystem as the XML structure is predefined. Only thing I need to do is assign value to the elements/attributes within the XML document.

     

     

    Tuesday, December 14, 2010 11:19 AM
  • Then once you load the xml document do this:

     

    XmlNode myNode= xmlDoc.SelectSingleNode("NameOfNode");

     

    to get the node required.

     

    If its a list of nodes then

    XmlNodeList myNodeList= xmlDoc.SelectNodes("NameOfNode"); //Will giev you a list of the nodes with the same name

     

    Setting attribute remains same..

    Tuesday, December 14, 2010 11:24 AM
  • XmlNode myNode= xmlDoc.SelectSingleNode("NameOfNode");

    XmlNodeList myNodeList= xmlDoc.SelectNodes("NameOfNode");


    These work only for the root node. To get nodes from anywhere in the document, use "//NameOfNode".
    Tuesday, December 14, 2010 3:24 PM
  • Am i the only one who thinks the System.Xml syntax looks like rubbish??

     

    Use System.Xml.Linq,

    private void CreateXmlDoc(string path)
     {
      // Load File
      XElement doc = XElement.Load(path);
    
      // Create new node, notice the indentation, The coding should
      // match the layout of your xml file. Just makes things easier!
      XElement newNode = new XElement("Person", new XAttribute("Name", "Tux"),
        new XElement("Age", 34),
        new XElement("Children", 1),
        new XElement("Married", false),
        new XElement("Pets",
          new XElement("Cats", "Billy,Fluffy"),
          new XElement("Dogs", "null")));
    
      // Add new person
      doc.Add(newNode);
    
      // Loop all people, assuming root is named "People"
      foreach (var person in doc.Elements("People")) ;
    
      // Grab a specific person
      string personToGet = "Tux";
      var me = doc.Elements("Person").Where(name => name.Attribute("Name").ToString() == personToGet);
     }
    

     

    Tuesday, December 14, 2010 3:34 PM