使用XmlSerializer类并为XmlElement和XmlRoot属性指定命名空间:
using System.Xml.Serialization;
...
// TODO: Move the namespace name to a const variable
[XmlRoot(ElementName = "Person", Namespace = "http://api.google.com/staticInfo/")]
public class Person
{
[XmlElement(ElementName="Id", Namespace="http://api.google.com/staticInfo/")]
public int ID { get; set; }
[XmlElement(ElementName = "age", Namespace = "http://api.google.com/staticInfo/")]
public int Age { get; set; }
}
...
string input =
@"<g1:Person xmlns:g1=""http://api.google.com/staticInfo/"">
<g1:Id>005008</g1:Id>
<g1:age>23</g1:age>
</g1:Person>";
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Person));
Person person = (Person)xmlSerializer.Deserialize(new StringReader(input));
或者,可以在 XmlSerializer 的构造函数中指定默认命名空间,并且不指定 Namespace 属性:
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Person),
"http://api.google.com/staticInfo/");
要确保命名空间前缀为“q1”,请指定要使用的XmlSerializerNamespaces。例如:
Person person; // Assuming it is populated as above
using(MemoryStream memoryStream = new MemoryStream())
{
xmlSerializer.Serialize(memoryStream, person,
new XmlSerializerNamespaces(new [] { new XmlQualifiedName("q1", "http://api.google.com/staticInfo/") }));
memoryStream.Flush();
Console.Out.WriteLine(Encoding.UTF8.GetChars(memoryStream.GetBuffer()));
}
表明:
<?xml version="1.0"?>
<q1:Person xmlns:q1="http://api.google.com/staticInfo/">
<q1:Id>5008</q1:Id>
<q1:age>23</q1:age>
</q1:Person>