C# writing attribute value into the element of the xml file

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • KYAW KYAW OO
    New Member
    • Jan 2007
    • 30

    C# writing attribute value into the element of the xml file

    Dear All,

    I am trying to write the xml file described as below

    XML for UnSelectedGameL ist.XML
    Code:
    <UnSelectedGameList>
    
      <game id="1" name="A" picture=@E:\Games\1.png" isSelected="0">
      </game>
    
    </UnSelectedGameList>
    I would like to update the attribute value of id and isSelected using data from left and right of list box controls. Then write as a new selectedgamelis t.xml.

    XML for SelectedGameLis t.XML
    Code:
    <SelectedGameList>
    
      <game id="1" name="A" picture=@"\Games\1.png" isSelected="0">
      </game>
    
    </SelectedGameList>
    I am looking forward to get any advice from someone in here.


    Thanks and best regards
  • vekipeki
    Recognized Expert New Member
    • Nov 2007
    • 229

    #2
    To make your properties serialize as attributes, you need to use the [XmlAttribute] attribute when defining your class, in your example it would be something like:

    Code:
    /*
    using System.Xml;
    using System.Xml.Serialization;
    */
    
    public class Game
    {
        private string _id;
        [XmlAttribute]
        public string ID
        {
            get { return _id; }
            set { _id = value; }
        }
    
        private string _name;
        [XmlAttribute]
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }
    
        // you get the idea
    }
    If you really need to have different xml element names for "selected" and "unselected " items, you can create something like this:

    Code:
    [XmlType("UnselectedGameList")]
    public class UnselectedGameList : List<Game> { }
    
    [XmlType("SelectedGameList")]
    public class SelectedGameList : List<Game> { }
    I presume you already know how to serialize/deserialize objects to/from xml. If not, here is a simple generic class that I use to do it quickly:

    XmlHelper

    You can add it to your project and then use it to serialize/deserialize your data:
    Code:
    // read from a file
    UnselectedGameList unselected =
        XmlHelper<UnselectedGameList>.Deserialize(@"UnselectedGameList.xml");
    
    // write to a file
    SelectedGameList selected = new SelectedGameList();
    XmlHelper<SelectedGameList>.Serialize(selected, @"SelectedGameList.xml");
    Note that these two files will have different Xml schemas, so you will always need two separate classes to handle them (what I am trying to say - I would normally use only a single file with a single Xml schema).

    Comment

    • mldisibio
      Recognized Expert New Member
      • Sep 2008
      • 191

      #3
      vekipeki - that is an awesome response...hand le all the attributes as properties of a class, then serialize, deserialize the object to xml - whoa...too cool.

      That said, my take on the post was the more old fashioned: I have an xml file, I want to load it from disk, find the correct element, update some attributes, and write it back to disk.

      For this you can use several classes from the System.Xml library as needed:
      XmlDocument to load and save a physical file from and to disk;
      XmlReader/Writer to read and write, if necessary.
      XmlNode and XmlAttributeCol lection to find a specific attribute and modify it.

      There are several similar approaches. Just to get you started, have a look at the example that comes with XmlNode.Attribu tes Property

      For small documents, these classes are fine. For large documents and heavy xml processing, the System.Xml.XPat h library is recommended, especially the XPathNavigator.

      If you can handle it, however, vekipeki's solution is the way to go.

      Comment

      • KYAW KYAW OO
        New Member
        • Jan 2007
        • 30

        #4
        Hi vekipeki and mldisibio

        Thank you for ur reply but I have still errors as below after
        instance = (T)xml.Deserial ize(sr);


        There is an error in XML document (1, 2).

        As for me, I am quite new for xmlSerializer and mldisibio is ok only for char like
        <game id="1" name="A" picture=" 1.png" isSelected="0"> </game>

        my application is to update the string of id = "1", "2" and so on
        and isSelected="0" to "1" or "1" to "0"


        I am looking for your advice coz I am in a hurry mode now.


        Best regards

        Comment

        • vekipeki
          Recognized Expert New Member
          • Nov 2007
          • 229

          #5
          Hello again, I am sorry I didn't read your message earlier, I just returned from my vacation.

          If you are still working on this, I believe that the problem could be the exact character casing (e.g. "Game" should be named "game", "ID" should be "id", according to your original file). I am sorry I didn't pay enough attention to the exact element names - my mistake.

          "There is an error in XML document (1, 2)." error tells you that the unexpected character was found in row 1, column 2 (that would be "g" if your file starts with "<game", which would indicate wrong casing, but open your .xml file in Notepad just to check exactly where the problem is). Check the exact spelling for "UnselectedGame List" also.

          You can either rename your class and properties, or add the desired Xml element names in the attributes for each property:

          Code:
          [XmlType("game")] // this will serialize Game as "game"
          public class Game
          {
              private string _id;
              [XmlAttribute("id")] // this will serialize ID as "id"
              public string ID
              {
                  get { return _id; }
                  set { _id = value; }
              }
          
              // ...
          }
          Also, if you want to omit xml namespace declaration (and Xml version <?xml version="1.0"?> ) , check Scott Hanselman's Computer Zen - XmlFragmentWrit er - Omiting the Xml Declaration and the XSD and XSI namespaces
          for an example of how to extend XmlTextWriter to skip "xmlns" and similar elements.

          Comment

          Working...