public class XmlConvert
|
Many languages and applications such as Microsoft SQL Server and Microsoft Word, allow Unicode characters in their names, which are not valid in XML names. For example, if 'Order Detail' were a column heading in a database, the database allows the space between the words Order and Detail. However, in XML, the space between Order and Detail is considered an invalid XML character. Thus, the space, the invalid character, needs to be converted into an escaped hexadecimal encoding and can be decoded later.
The EncodeName method can be used with the XmlTextWriter class to ensure the names being written are valid XML names. The following C# code converts the name 'Order Detail' into a valid XML name and writes the element
<Order_0x0020_Detail>My
order</Order_0x0020_Detail>
.
writer.WriteElementString(XmlConvert.EncodeName("Order Detail"),"My order");
XmlConvert also provides methods that enable you to convert from a string to a .NET Framework data type and vice-versa. Locale settings are not taken into account during data conversion. The data types are based on the XML Schema (XSD) data types. The table found at the conceptual topic at MSDN: datatypesupportbetweenxsdtypesnetframeworktypes describes the mapping between XML Schema (XSD) and .NET data types.
In the following example, the XmlTextReader uses one of the XmlConvert.ToDouble method to read in data and convert it from a String to a Double.
Double price = XmlConvert.ToDouble(reader.Value);
ctor #1 | Default constructor. This constructor is called by derived class constructors to initialize state in this type. |
DecodeName | Decodes a name. This method does the reverse of the XmlConvert.EncodeName and XmlConvert.EncodeLocalName methods. |
EncodeLocalName | Converts the name to a valid XML local name. |
EncodeName | Converts the name to a valid XML name. |
EncodeNmToken | Verifies the name is valid according to the XML specification. |
Equals (inherited from System.Object) |
See base class member description: System.Object.Equals Derived from System.Object, the primary base class for all objects. |
GetHashCode (inherited from System.Object) |
See base class member description: System.Object.GetHashCode Derived from System.Object, the primary base class for all objects. |
GetType (inherited from System.Object) |
See base class member description: System.Object.GetType Derived from System.Object, the primary base class for all objects. |
ToBoolean | Converts the String to a Boolean equivalent. |
ToByte | Converts the String to a Byte equivalent. |
ToChar | Converts the String to a Char equivalent. |
ToDateTime | Overloaded:ToDateTime(string s) Converts the String to a DateTime equivalent. |
ToDateTime | Overloaded:ToDateTime(string s, string format) Converts the String to a DateTime equivalent. |
ToDateTime | Overloaded:ToDateTime(string s, string[] formats) Converts the String to a DateTime equivalent. |
ToDecimal | Converts the String to a Decimal equivalent. |
ToDouble | Converts the String to a Double equivalent. |
ToGuid | Converts the String to a Guid equivalent. |
ToInt16 | Converts the String to a Int16 equivalent. |
ToInt32 | Converts the String to a Int32 equivalent. |
ToInt64 | Converts the String to a Int64 equivalent. |
ToSByte | Converts the String to a SByte equivalent. |
ToSingle | Converts the String to a Single equivalent. |
ToString (inherited from System.Object) |
Overloaded:ToString() See base class member description: System.Object.ToStringDerived from System.Object, the primary base class for all objects. |
ToString | Overloaded:ToString(bool value) Converts the Boolean to a String. |
ToString | Overloaded:ToString(byte value) Converts the Byte to a String. |
ToString | Overloaded:ToString(char value) Converts the Char to a String. |
ToString | Overloaded:ToString(DateTime value) Converts the DateTime to a String. |
ToString | Overloaded:ToString(decimal value) Converts the Decimal to a String. |
ToString | Overloaded:ToString(double value) Converts the Double to a String. |
ToString | Overloaded:ToString(Guid value) Converts the Guid to a String. |
ToString | Overloaded:ToString(short value) Converts the Int16 to a String. |
ToString | Overloaded:ToString(int value) Converts the Int32 to a String. |
ToString | Overloaded:ToString(long value) Converts the Int64 to a String. |
ToString | Overloaded:ToString(sbyte value) Converts the SByte to a String. |
ToString | Overloaded:ToString(float value) Converts the Single to a String. |
ToString | Overloaded:ToString(TimeSpan value) Converts the TimeSpan to a String. |
ToString | Overloaded:ToString(ushort value) Converts the UInt16 to a String. |
ToString | Overloaded:ToString(uint value) Converts the UInt32 to a String. |
ToString | Overloaded:ToString(ulong value) Converts the UInt64 to a String. |
ToString | Overloaded:ToString(DateTime value, string format) Converts the DateTime to a String. |
ToTimeSpan | Converts the String to a TimeSpan equivalent. |
ToUInt16 | Converts the String to a UInt16 equivalent. |
ToUInt32 | Converts the String to a UInt32 equivalent. |
ToUInt64 | Converts the String to a UInt64 equivalent. |
VerifyName | Verifies that the name is a valid name according to the W3C Extended Markup Language recommendation. |
VerifyNCName | Verifies that the name is a valid NCName according to the W3C Extended Markup Language recommendation. |
Finalize (inherited from System.Object) |
See base class member description: System.Object.Finalize Derived from System.Object, the primary base class for all objects. |
MemberwiseClone (inherited from System.Object) |
See base class member description: System.Object.MemberwiseClone Derived from System.Object, the primary base class for all objects. |
Hierarchy:
public XmlConvert(); |
name
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { // Encode and decode a name with spaces. string name1 = XmlConvert.EncodeName("Order Detail"); Console.WriteLine("Encoded name: " + name1); Console.WriteLine("Decoded name: " + XmlConvert.DecodeName(name1)); // Encode and decode a local name. string name2 = XmlConvert.EncodeLocalName("a:book"); Console.WriteLine("Encoded local name: " + name2); Console.WriteLine("Decoded local name: " + XmlConvert.DecodeName(name2)); } }
name
For example, if you passed this method the invalid name a:b, it returns a_x003a_b, which is a valid local name.
If name is null or String.Empty then you get the same value returned.
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { // Encode and decode a name with spaces. string name1 = XmlConvert.EncodeName("Order Detail"); Console.WriteLine("Encoded name: " + name1); Console.WriteLine("Decoded name: " + XmlConvert.DecodeName(name1)); // Encode and decode a local name. string name2 = XmlConvert.EncodeLocalName("a:book"); Console.WriteLine("Encoded local name: " + name2); Console.WriteLine("Decoded local name: " + XmlConvert.DecodeName(name2)); } }
name
The escape character is "_". Any XML name character that does not conform to the W3C Extensible Markup Language (XML) 1.0 specification is escaped as _xHHHH_. The HHHH string stands for the four-digit hexadecimal UCS-2 code for the character in most significant bit first order. For example, the name Order Details is encoded as Order_x0020_Details.
The underscore character does not need to be escaped unless it is followed by a character sequence that together with the underscore can be misinterpreted as an escape sequence when decoding the name. For example, Order_Details is not encoded, but Order_x0020_ is encoded as Order_x005f_x0020_. No shortforms are allowed. For example, the forms _x20_ and __ are not generated.
This method guarantees the name is valid according to the XML specification. It allows colons in any position, which means the name may still be invalid according to the W3C Namespace Specification (www.w3.org/TR/REC-xml-names). To guarantee it is a valid namespace qualified name use XmlConvert.EncodeLocalName for the prefix and local name parts and join the result with a colon.
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { // Encode and decode a name with spaces. string name1 = XmlConvert.EncodeName("Order Detail"); Console.WriteLine("Encoded name: " + name1); Console.WriteLine("Decoded name: " + XmlConvert.DecodeName(name1)); // Encode and decode a local name. string name2 = XmlConvert.EncodeLocalName("a:book"); Console.WriteLine("Encoded local name: " + name2); Console.WriteLine("Decoded local name: " + XmlConvert.DecodeName(name2)); } }
name
If name is null or String.Empty then you get the same value returned.
~XmlConvert(); |
public virtual int GetHashCode(); |
public Type GetType(); |
protected object MemberwiseClone(); |
s
s
s
Exception Type | Condition |
---|---|
ArgumentNullException | The value of the s parameter is null. |
FormatException | The s parameter contains more than one character. |
s
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlTextReader reader = new XmlTextReader("orderData.xml"); //Parse the file and pull out the order date and price. while (reader.Read()){ if (reader.NodeType==XmlNodeType.Element){ switch(reader.Name){ case "order": DateTime orderDate = XmlConvert.ToDateTime(reader.GetAttribute("date")); Console.WriteLine("order date: {0}", orderDate.ToString()); break; case "price": Double price = XmlConvert.ToDouble(reader.ReadInnerXml()); Console.WriteLine("price: {0}", price.ToString()); break; } } } //Close the reader. reader.Close(); } }The example uses the file, orderData.xml, as input.
<order date="2001-05-03"> <orderID>367A54</orderID> <custID>32632</custID> <price>19.95</price> </order>
s
format
s
formats
s
s
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlTextReader reader = new XmlTextReader("orderData.xml"); //Parse the file and pull out the order date and price. while (reader.Read()){ if (reader.NodeType==XmlNodeType.Element){ switch(reader.Name){ case "order": DateTime orderDate = XmlConvert.ToDateTime(reader.GetAttribute("date")); Console.WriteLine("order date: {0}", orderDate.ToString()); break; case "price": Double price = XmlConvert.ToDouble(reader.ReadInnerXml()); Console.WriteLine("price: {0}", price.ToString()); break; } } } //Close the reader. reader.Close(); } }The example uses the file, orderData.xml, as input.
<order date="2001-05-03"> <orderID>367A54</orderID> <custID>32632</custID> <price>19.95</price> </order>
s
s
s
s
s
s
public virtual string ToString(); |
value
value
value
value
value
value
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { //Define the order data. They will be converted to string //before being written out. Int16 custID = 32632; String orderID = "367A54"; DateTime orderDate = new DateTime(); orderDate = DateTime.Now; Double price = 19.95; //Create a writer that outputs to the console. XmlTextWriter writer = new XmlTextWriter (Console.Out); writer.Formatting = Formatting.Indented; //Write an element (this one is the root) writer.WriteStartElement("order"); //Write the order date. writer.WriteAttributeString("date", XmlConvert.ToString(orderDate, "yyyy-MM-dd")); //Write the order time. writer.WriteAttributeString("time", XmlConvert.ToString(orderDate, "HH:mm:ss")); //Write the order data. writer.WriteElementString("orderID", orderID); writer.WriteElementString("custID", XmlConvert.ToString(custID)); writer.WriteElementString("price", XmlConvert.ToString(price)); //Write the close tag for the root element writer.WriteEndElement(); //Write the XML and close the writer writer.Close(); } }
value
value
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { //Define the order data. They will be converted to string //before being written out. Int16 custID = 32632; String orderID = "367A54"; DateTime orderDate = new DateTime(); orderDate = DateTime.Now; Double price = 19.95; //Create a writer that outputs to the console. XmlTextWriter writer = new XmlTextWriter (Console.Out); writer.Formatting = Formatting.Indented; //Write an element (this one is the root) writer.WriteStartElement("order"); //Write the order date. writer.WriteAttributeString("date", XmlConvert.ToString(orderDate, "yyyy-MM-dd")); //Write the order time. writer.WriteAttributeString("time", XmlConvert.ToString(orderDate, "HH:mm:ss")); //Write the order data. writer.WriteElementString("orderID", orderID); writer.WriteElementString("custID", XmlConvert.ToString(custID)); writer.WriteElementString("price", XmlConvert.ToString(price)); //Write the close tag for the root element writer.WriteEndElement(); //Write the XML and close the writer writer.Close(); } }
value
value
value
value
value
value
value
value
value
format
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { //Define the order data. They will be converted to string //before being written out. Int16 custID = 32632; String orderID = "367A54"; DateTime orderDate = new DateTime(); orderDate = DateTime.Now; Double price = 19.95; //Create a writer that outputs to the console. XmlTextWriter writer = new XmlTextWriter (Console.Out); writer.Formatting = Formatting.Indented; //Write an element (this one is the root) writer.WriteStartElement("order"); //Write the order date. writer.WriteAttributeString("date", XmlConvert.ToString(orderDate, "yyyy-MM-dd")); //Write the order time. writer.WriteAttributeString("time", XmlConvert.ToString(orderDate, "HH:mm:ss")); //Write the order data. writer.WriteElementString("orderID", orderID); writer.WriteElementString("custID", XmlConvert.ToString(custID)); writer.WriteElementString("price", XmlConvert.ToString(price)); //Write the close tag for the root element writer.WriteEndElement(); //Write the XML and close the writer writer.Close(); } }
s
s
s
s
name
Exception Type | Condition |
---|---|
XmlException | The name is not a valid XML name. |
try{ writer.WriteStartElement(XmlConvert.VerifyName("item"),"bar"); } catch(Exception e) { Console.WriteLine("error"); }
using System; using System.Xml; public class Sample{ public static void Main(){ XmlTextWriter writer = new XmlTextWriter ("out.xml", null); string tag = "item name"; try{ // Write the root element. writer.WriteStartElement("root"); writer.WriteStartElement(XmlConvert.VerifyName(tag)); } catch (Exception e){ Console.WriteLine(e.Message); Console.WriteLine("Convert to a valid name..."); writer.WriteStartElement(XmlConvert.EncodeName(tag)); } writer.WriteString("hammer"); writer.WriteEndElement(); // Write the end tag for the root element. writer.WriteEndElement(); writer.Close(); } }
name