XAttribute value
In this chapter you will learn:
- Access value from XAttribute
- Cast the value of this XAttribute to a Boolean.
- Cast the value of this XAttribute to a DateTime.
- How to set value for XAttribute
Access value from XAttribute
XAttribute.Value
gets or sets the value of this attribute.
using System;/*from ja v a 2 s . c om*/
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Collections;
using System.Collections.Generic;
public class MainClass{
public static void Main(){
XElement root = new XElement("Root",
new XAttribute("Att", "content")
);
XAttribute att = root.FirstAttribute;
Console.WriteLine(att.Value);
att.Value = "new text";
Console.WriteLine(att.Value);
}
}
Cast the value of this XAttribute to a Boolean.
using System;/*j a v a 2 s.c o m*/
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Collections;
using System.Collections.Generic;
public class MainClass{
public static void Main(){
XElement root = new XElement("Root",
new XAttribute("BoolValue", true)
);
bool bv = (bool)root.Attribute("BoolValue");
Console.WriteLine("(bool)BoolValue={0}", bv);
}
}
Cast the value of this XAttribute to a DateTime.
using System;/*from ja v a 2 s . c om*/
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Collections;
using System.Collections.Generic;
public class MainClass{
public static void Main(){
XElement root = new XElement("Root",
new XAttribute("Att", new DateTime(2010, 10, 6, 12, 30, 0))
);
Console.WriteLine(root);
DateTime dt = (DateTime)root.Attribute("Att");
Console.WriteLine("dt={0}", dt);
XAttribute dtAtt = new XAttribute("OrderDate", "October 6, 2006");
Console.WriteLine(dtAtt);
DateTime orderDate = (DateTime)dtAtt;
Console.WriteLine("OrderDate={0:d}", orderDate);
}
}
set value for XAttribute
XAttribute.SetValue sets the value of this attribute.
using System;//from jav a2 s . c o m
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Collections;
using System.Collections.Generic;
public class MainClass{
public static void Main(){
XElement root = new XElement("Root",
new XAttribute("Att1", "content1"),
new XAttribute("Att2", "content2"),
new XAttribute("Att3", "content3")
);
XAttribute att = root.Attribute("Att2");
att.SetValue("new content");
Console.WriteLine(root);
}
}
Next chapter...
What you will learn in the next chapter:
Home » C# Tutorial » XML Linq