473,396 Members | 1,755 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

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 UnSelectedGameList.XML
Expand|Select|Wrap|Line Numbers
  1. <UnSelectedGameList>
  2.  
  3.   <game id="1" name="A" picture=@E:\Games\1.png" isSelected="0">
  4.   </game>
  5.  
  6. </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 selectedgamelist.xml.

XML for SelectedGameList.XML
Expand|Select|Wrap|Line Numbers
  1. <SelectedGameList>
  2.  
  3.   <game id="1" name="A" picture=@"\Games\1.png" isSelected="0">
  4.   </game>
  5.  
  6. </SelectedGameList>
I am looking forward to get any advice from someone in here.


Thanks and best regards
Jan 2 '09 #1
4 9655
vekipeki
229 Expert 100+
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:

Expand|Select|Wrap|Line Numbers
  1. /*
  2. using System.Xml;
  3. using System.Xml.Serialization;
  4. */
  5.  
  6. public class Game
  7. {
  8.     private string _id;
  9.     [XmlAttribute]
  10.     public string ID
  11.     {
  12.         get { return _id; }
  13.         set { _id = value; }
  14.     }
  15.  
  16.     private string _name;
  17.     [XmlAttribute]
  18.     public string Name
  19.     {
  20.         get { return _name; }
  21.         set { _name = value; }
  22.     }
  23.  
  24.     // you get the idea
  25. }
  26.  
If you really need to have different xml element names for "selected" and "unselected" items, you can create something like this:

Expand|Select|Wrap|Line Numbers
  1. [XmlType("UnselectedGameList")]
  2. public class UnselectedGameList : List<Game> { }
  3.  
  4. [XmlType("SelectedGameList")]
  5. 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:
Expand|Select|Wrap|Line Numbers
  1. // read from a file
  2. UnselectedGameList unselected =
  3.     XmlHelper<UnselectedGameList>.Deserialize(@"UnselectedGameList.xml");
  4.  
  5. // write to a file
  6. SelectedGameList selected = new SelectedGameList();
  7. 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).
Jan 2 '09 #2
mldisibio
190 Expert 100+
vekipeki - that is an awesome response...handle 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 XmlAttributeCollection 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.Attributes Property

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

If you can handle it, however, vekipeki's solution is the way to go.
Jan 2 '09 #3
Hi vekipeki and mldisibio

Thank you for ur reply but I have still errors as below after
instance = (T)xml.Deserialize(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
Jan 3 '09 #4
vekipeki
229 Expert 100+
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 "UnselectedGameList" also.

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

Expand|Select|Wrap|Line Numbers
  1. [XmlType("game")] // this will serialize Game as "game"
  2. public class Game
  3. {
  4.     private string _id;
  5.     [XmlAttribute("id")] // this will serialize ID as "id"
  6.     public string ID
  7.     {
  8.         get { return _id; }
  9.         set { _id = value; }
  10.     }
  11.  
  12.     // ...
  13. }
  14.  
Also, if you want to omit xml namespace declaration (and Xml version <?xml version="1.0"?>) , check Scott Hanselman's Computer Zen - XmlFragmentWriter - Omiting the Xml Declaration and the XSD and XSI namespaces
for an example of how to extend XmlTextWriter to skip "xmlns" and similar elements.
Jan 12 '09 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: j erickson | last post by:
with the following xsl and xml file, the display of the gif file with the <image/url> tag works. However, the gif file in the <description> tag using the name attribute "src" won't make the correct...
4
by: Lénaïc Huard | last post by:
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hello, I've some namespace problems when defining default values for attributes. My problem seems to come from the fact that the attributes are...
2
by: Bill Cohagan | last post by:
In my app I'm validating an XML file against an XSD which contains several attribute default value specifications. I'm performing the validation via an xml document load() using a...
2
by: Ian Griffiths | last post by:
I have been given a schema, instances of which I'm required to be able to consume and generate. I'd like to be able to manipulate these instances as DataSets internally in my application. The...
1
by: arnold | last post by:
Hi, I've been knocking my head against the wall trying to create an XSL transform to perform "normalizations" of a set of XML files that have a common structure. % XML file before transform
3
by: Eric | last post by:
Help! I created a XML schema with a Visual Studio tools. I'm filling a dataset with a DataAdapter. Before I use the "WriteXml" method to write the data to a xml file, I want to map the XSD file I...
8
by: patrizio.trinchini | last post by:
Hi All, I'would like to write an XSL transformation that changes the value of the atribute of a given element according to the value of another atttribute of the same element. For instance,...
3
by: patrizio.trinchini | last post by:
Hi, how can remove sibling elements based on the value of an attribute ? For instance, gven the XML document: <root> <parentElment> <testElement name="A"> <removableElement/>
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.