XML Tricks for C# - Attributes and Document Complexity
(Page 2 of 5 )
When you write your XML document using elements only, your document size will be larger and more difficult to read than writing it using attributes. Let's consider the following XML Document:
<?xml version="1.0"? >
<Consultants>
<Consultant>
<name>Michael Youssef</name>
<position>XML Consultant</position>
<age>21</age>
</Consultant>
<Consultant>
<name>Prakhar Deva</name>
<position>.NET Consultant</position>
<age>23</age>
</Consultant>
</Consultants>
We can rewrite this XML document better by using attributes.
<?xml version="1.0"? >
<Consultants>
<Consultant position="Microsoft.NET Consultant" age="21">Michael Youssef</Consultant>
<Consultant position=".NET Developer" age="23">Prakhar Deva</Consultant>
</Consultants>
Now our document is much more readable and efficient (5 lines instead of 13).
Until now, I've told you about why you should use attributes. Now, let me tell you also why you should use elements.
Use elements when you need a complex structure.
When you build a complex structure you have to consider using elements. Consider the following invalid XML document:
< ? xml version="1.0" ? >
<members>
<member phone number="0020123658513" phone number="3331684">Michael Youssef</member>
</members>
Here each member has two phone numbers. This is invalid because you can't have two attributes with the same name in one element. It will be better logically if you rewrite these phone number attributes as elements so you can know for certain that this person has 2 phone numbers. Let's rewrite the document again.
< ? xml version="1.0" ? >
<members>
<member name="Michael Youssef">
<phoneNumber>0020123658513</phoneNumber>
<phoneNumber>3331684</phoneNumber>
</member>
</members>
It's up to you (your experience and the situation) to use elements or attributes. I've shown you some advantages of using both so make sure that you understand this article. But if you have a complex structure to build then definitely you need to use elements. You could also gain some useful information by extracting some data from a SQL Server 2000 database into XML documents and see how the documents are structured.
Now let's go to our second subject, encoding.
Next: A First Look at Encoding >>
More XML Articles
More By Michael Youssef