我有一个XML:
<g1:Person xmlns:g1="http://api.google.com/staticInfo/">
<g1:Id> 005008</g1:Id>
<g1:age>23></g1:age>
</g1:Person>
如何将其反序列化为Person Object。
我找到了一条路。
XmlDocument xdc = new XmlDocument();
xdc.Load(xmlpath);
xdc.LoadXml(xdc.InnerXml.Replace("g1:",""));
xdc.Save(xmlpath);
使其变得简单的任何其他方法。或者是一种先进的方法。
xs = new XmlSerializer(typeof(Person));
XmlDocument xdc = new XmlDocument();
xdc.Load(xmlpath);
xdc.LoadXml(xdc.InnerXml.Replace("g1:",""));
xdc.Save(xmlpath);
Stream stm = new FileStream(xmlpath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
Person p= xs.Deserialize(stm) as Person;
答案 0 :(得分:4)
使用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>