How to use Attribute in XML

In this article I have described the attribute used in XML application with the help of example.
  • 2085

XML Attribute

  • It is possible to attach additional information to elements in the form of attributes .
  • In XML, like HTML, an attribute is a part of an element that provides additional information about that element.
  • XML elements can have attributes in the start tag, just like HTML.
  • Attributes have a name and a value. The names follow the same rules as element names.
  • Elements can have one or more attributes in the start tag, and the name is separated from the value by the equal character.
  • The value of the attribute is enclosed in double or single quotation marks.

Syntax of  XML Attribute

XML requires that all XML attributes have a value not same in HTML . The syntax of XML attribute is as follows

<tag attribute="value">Data</tag>

Example

<tutorials published="true">
   <tutorial>
      <name>XML</name>
   </tutorial>
</tutorials>

NOTE - The attribute published is valid because we set it to a value true. Here is an example of shorthand that is sometimes used in HTML, but is not valid XML.

XML Code:

<tutorials published>
   <tutorial>
    <name>XML</name>
  </tutorial>
</tutorials>

This XML attribute is wrong because it was not set to a value.

Quotes

As I have described above that  Attribute values must always be enclosed in quotes. Use either single or double quotes .

<color="red">
or
<color='red'>

For example, the type element can have a preferred attribute

<tutorials type="Web">
  <tutorial>
    <name>XML</name>
  </tutorial>
</tutorials>

Unlike HTML, XML insists on the quotation marks . The XML processor would reject the following

<tutorials type=Web>
 <tutorial>
    <name>XML</name>
  </tutorial>
</tutorials>

The quotation marks can be either single or double quotes.

Further Readings

You may also want to read these related articles :

Ask Your Question 

Got a programming related question? You may want to post your question here

Programming Answers here

© 2019 DotNetHeaven. All rights reserved.